diff --git a/docs/technical/api/admin/authorization/Api.Permissions.md b/docs/technical/api/admin/authorization/Api.Permissions.md new file mode 100644 index 00000000..e18a7b9a --- /dev/null +++ b/docs/technical/api/admin/authorization/Api.Permissions.md @@ -0,0 +1,36 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Permissions](#permissions) + - [Get Permissions](#get-permissions) + - [Get Permissions Request](#get-permissions-request) + - [Get Permissions Response](#get-permissions-response) + +## Permissions + +### Get Permissions + +#### Get Permissions Request + +```js +GET api/v1/auth/permissions +``` + +#### Get Permissions Response + +```js +200 Ok +``` + +```json +[ + { + "id": "5264e3a8-bdec-4ec0-9423-839f3a9afe4b", + "permissionName": "CanDeleteUsers" + }, + { + "id": "7830cd55-3585-4da1-bfad-994be8637da8", + "permissionName": "CanViewUsers" + } +] +``` diff --git a/docs/technical/api/admin/authorization/Api.Roles.md b/docs/technical/api/admin/authorization/Api.Roles.md new file mode 100644 index 00000000..43b56b22 --- /dev/null +++ b/docs/technical/api/admin/authorization/Api.Roles.md @@ -0,0 +1,182 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Roles](#roles) + - [Get Roles](#get-roles) + - [Get Roles Request](#get-roles-request) + - [Get Roles Response](#get-roles-response) + - [Get Role Permissions](#get-role-permissions) + - [Get Role Permissions Request](#get-role-permissions-request) + - [Get Role Permissions Response](#get-role-permissions-response) + - [Add Role](#add-role) + - [Add Role Request](#add-role-request) + - [Add Role Response](#add-role-response) + - [Update Role](#update-role) + - [Update Role Request](#update-role-request) + - [Update Role Response](#update-role-response) + - [Delete Role](#delete-role) + - [Delete Role Request](#delete-role-request) + - [Delete Role Response](#delete-role-response) + +## Roles + +### Get Roles + +#### Get Roles Request + +```js +GET api/v1/auth/roles +``` + +#### Get Roles Response + +```js +200 Ok +``` + +```json +[ + { + "id": "776e440d-39d2-4f31-8dcd-481de61e8792", + "roleName": "Admin" + } +] +``` + + +### Get Role Permissions + +#### Get Role Permissions Request + +```js +GET api/v1/auth/roles/{roleId}/permissions +``` + +#### Get Role Permissions Response + +```js +200 Ok +``` + +```json +{ + "role": { + "id": "61567253-c752-4680-989c-a40a73f3e4b9", + "roleName": "Editor" + }, + "permissions": [ + { + "id": "5264e3a8-bdec-4ec0-9423-839f3a9afe4b", + "permissionName": "CanDeleteUsers" + }, + { + "id": "7830cd55-3585-4da1-bfad-994be8637da8", + "permissionName": "CanViewUsers" + } + ] +} +``` + + +### Add Role + +#### Add Role Request + +```js +POST api/v1/auth/roles +``` + +```json +{ + "roleName": "Editor", + "permissions": [ + "7934ff13-1ccd-4c24-bab3-6423c905e249", + "8f23e43a-bb4b-483a-99eb-7ab361df7482" + ] +} +``` + +#### Add Role Response + +```js +200 Ok +``` + +```json +{ + "role": { + "id": "e5b67972-6928-4be1-a757-e98879d4a12a", + "roleName": "Editor" + }, + "permissions": [ + { + "id": "7934ff13-1ccd-4c24-bab3-6423c905e249", + "permissionName": "CanDeleteUsers" + }, + { + "id": "8f23e43a-bb4b-483a-99eb-7ab361df7482", + "permissionName": "CanViewUsers" + } + ] +} +``` + + +### Update Role + +#### Update Role Request + +```js +PUT api/v1/auth/roles +``` + +```json +{ + "roleId": "73d204e2-5922-441d-83d8-8d4d8fc29eaa", + "roleName": "Editor", + "permissions": [ + "ac113d18-69bb-4162-8c05-ff7a5559059a", + "3c2fd936-8d4a-4963-b237-9f8d3aeeab26" + ] +} +``` + +#### Update Role Response + +```js +200 Ok +``` + +```json +{ + "role": { + "id": "61567253-c752-4680-989c-a40a73f3e4b9", + "roleName": "Editor" + }, + "permissions": [ + { + "id": "5264e3a8-bdec-4ec0-9423-839f3a9afe4b", + "permissionName": "CanDeleteUsers" + }, + { + "id": "7830cd55-3585-4da1-bfad-994be8637da8", + "permissionName": "CanViewUsers" + } + ] +} +``` + + +### Delete Role + +#### Delete Role Request + +```js +DELETE api/v1/auth/roles/{roleId} +``` + +#### Delete Role Response + +```js +204 No Content +``` diff --git a/docs/technical/api/file-system-management/Api.Directories.md b/docs/technical/api/file-system-management/Api.Directories.md index cd57e035..b1fc79e6 100644 --- a/docs/technical/api/file-system-management/Api.Directories.md +++ b/docs/technical/api/file-system-management/Api.Directories.md @@ -16,7 +16,7 @@ ##### Get Directories Request ```js -GET api/v1/directories/get-directories?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET api/v1/directories/get-directories?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true ``` ##### Get Directories Response diff --git a/docs/technical/api/file-system-management/Api.Files.md b/docs/technical/api/file-system-management/Api.Files.md index 41b33576..2b6ae344 100644 --- a/docs/technical/api/file-system-management/Api.Files.md +++ b/docs/technical/api/file-system-management/Api.Files.md @@ -19,7 +19,7 @@ ##### Get Files Request ```js -GET api/v1/files/get-files?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET api/v1/files/get-files?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true ``` ##### Get Files Response @@ -52,7 +52,7 @@ GET api/v1/files/get-files?path=C%3A%5CUsers%5C&includeHiddenElements=true ##### Get Tree Files Request ```js -GET api/v1/files/get-tree-files?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET api/v1/files/get-tree-files?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true ``` ##### Get Tree Files Response diff --git a/docs/technical/api/file-system-management/Api.Path.md b/docs/technical/api/file-system-management/Api.Path.md index 251cb768..61042176 100644 --- a/docs/technical/api/file-system-management/Api.Path.md +++ b/docs/technical/api/file-system-management/Api.Path.md @@ -34,7 +34,7 @@ ##### Check Path Exists Request ```js -GET api/v1/path/check-path-exists?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET api/v1/path/check-path-exists?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true ``` ##### Check Path Exists Response 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 new file mode 100644 index 00000000..0a08db52 --- /dev/null +++ b/docs/technical/api/library/audio-library/music-library/Api.Albums.md @@ -0,0 +1,1054 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Album](#album) + - [Add Album](#add-album) + - [Add Album Request](#add-album-request) + - [Add Album Response](#add-album-response) + - [Get Artist Albums](#get-artist-albums) + - [Get Artist Albums Request](#get-artist-albums-request) + - [Get Artist Albums Response](#get-artist-albums-response) + - [Get Artist Albums Lite](#get-artist-albums-lite) + - [Get Artist Albums Lite Request](#get-artist-albums-lite-request) + - [Get Artist Albums Lite Response](#get-artist-albums-lite-response) + - [Get Album](#get-album) + - [Get Album Request](#get-album-request) + - [Get Album Response](#get-album-response) + - [Update Album](#update-album) + - [Update Album Request](#update-album-request) + - [Update Album Response](#update-album-response) + - [Delete Album](#delete-album) + - [Get Album Tracks](#get-album-tracks) + - [Get Album Tracks Request](#get-album-tracks-request) + - [Get Album Tracks Response](#get-album-tracks-response) + - [Get Album Tracks Lite](#get-album-tracks-lite) + - [Get Album Tracks Lite Request](#get-album-tracks-lite-request) + - [Get Album Tracks Lite Response](#get-album-tracks-lite-response) + +## Album + +### Add Album + +#### Add Album Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums +``` + +```json +{ + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ] + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", + "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "moods": [ + { "name": "dramatic" }, + { "name": "anxious" } + ], + "isrcs": [ + { "value": "GBUM71029604" } + ] + }, + { + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Pop Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "love" } + ] + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", + "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ], + "moods": [ + { "name": "happy" }, + { "name": "warm" } + ], + "isrcs": [ + { "value": "GBUM71029609" } + ] + } + ] +} +``` + +#### Add Album Response + +```js +201 Created +``` + +```json +{ + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "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.", + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { + "name": "Rock" + }, + { + "name": "Progressive Rock" + } + ], + "tags": [ + { + "name": "classic" + }, + { + "name": "vinyl" + } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "contributors": [ + { + "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", + "role": "Producer" + }, + { + "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", + "role": "Engineer" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } + ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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, + "contributors": [ + { + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "moods": [ + { "name": "dramatic" }, + { "name": "anxious" } + ], + "isrcs": [ + { "value": "GBUM71029604" } + ] + }, + { + "id": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } + ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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, + "contributors": [ + { + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ], + "moods": [ + { "name": "happy" }, + { "name": "warm" } + ], + "isrcs": [ + { "value": "GBUM71029609" } + ] + } + ] +} +``` + + +### Get Artist Albums + +#### Get Artist Albums Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums +``` + +#### Get Artist Albums Response + +```js +200 Ok +``` + +```json +[ + { + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "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.", + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { + "name": "Rock" + }, + { + "name": "Progressive Rock" + } + ], + "tags": [ + { + "name": "classic" + }, + { + "name": "vinyl" + } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "contributors": [ + { + "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", + "role": "Producer" + }, + { + "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", + "role": "Engineer" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [] + } +] +``` + + +### Get Artist Albums Lite + +#### Get Artist Albums Lite Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/lite?currentPage=1&perPage=10 +``` + +| Query Parameter | Type | Description | +| --- | --- | --- | +| `currentPage` | `int` | Optional. The page of results to retrieve. | +| `perPage` | `int` | Optional. The maximum number of albums to retrieve per page. | + +#### Get Artist Albums Lite Response + +```js +200 Ok +``` + +```json +{ + "data": [ + { + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "title": "A Night at the Opera", + "totalTracks": 12 + } + ], + "currentPage": 1, + "perPage": 10, + "count": 1, + "numberOfPages": 1 +} +``` + + +### Get Album + +#### Get Album Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +``` + +#### Get Album Response + +```js +200 Ok +``` + +```json +{ + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "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.", + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { + "name": "Rock" + }, + { + "name": "Progressive Rock" + } + ], + "tags": [ + { + "name": "classic" + }, + { + "name": "vinyl" + } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "contributors": [ + { + "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", + "role": "Producer" + }, + { + "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", + "role": "Engineer" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [] +} +``` + + +### Update Album + +#### Update Album Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +``` + +```json +{ + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} +``` + +#### Update Album Response + +```js +200 Ok +``` + +```json +{ + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "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.", + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { + "name": "Rock" + }, + { + "name": "Progressive Rock" + } + ], + "tags": [ + { + "name": "classic" + }, + { + "name": "vinyl" + } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "contributors": [ + { + "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", + "role": "Producer" + }, + { + "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", + "role": "Engineer" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [] +} +``` + + +### Delete Album + +```js +DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{albumId} +``` + +```js +200 Ok +``` + +Deletes the album identified by the route, together with its tracks. An artist must always keep at least one album. + + +### Get Album Tracks + +#### Get Album Tracks Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +``` + +#### Get Album Tracks Response + +```js +200 Ok +``` + +```json +[ + { + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + } +] +``` + + +### Get Album Tracks Lite + +#### Get Album Tracks Lite Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/lite?currentPage=1&perPage=10 +``` + +| Query Parameter | Type | Description | +| --- | --- | --- | +| `currentPage` | `int` | Optional. The page of results to retrieve. | +| `perPage` | `int` | Optional. The maximum number of tracks to retrieve per page. | + +#### Get Album Tracks Lite Response + +```js +200 Ok +``` + +```json +{ + "data": [ + { + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "title": "Bohemian Rhapsody", + "trackNumber": 1, + "discNumber": 1 + } + ], + "currentPage": 1, + "perPage": 10, + "count": 1, + "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 new file mode 100644 index 00000000..94ddad92 --- /dev/null +++ b/docs/technical/api/library/audio-library/music-library/Api.Artists.md @@ -0,0 +1,1085 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Artist](#artist) + - [Add Artist](#add-artist) + - [Add Artist Request](#add-artist-request) + - [Add Artist Response](#add-artist-response) + - [Get Artists](#get-artists) + - [Get Artists Request](#get-artists-request) + - [Get Artists Response](#get-artists-response) + - [Get Artists Lite](#get-artists-lite) + - [Get Artists Lite Request](#get-artists-lite-request) + - [Get Artists Lite Response](#get-artists-lite-response) + - [Get Artist](#get-artist) + - [Get Artist Request](#get-artist-request) + - [Get Artist Response](#get-artist-response) + - [Update Artist](#update-artist) + - [Update Artist Request](#update-artist-request) + - [Update Artist Response](#update-artist-response) + - [Delete Artist](#delete-artist) + +## Artist + +### Add Artist + +#### Add Artist Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists +``` + +```json +{ + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12 + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } + ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + }, + { + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } + ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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" } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ] + } + ] + } + ] +} +``` + +#### Add Artist Response + +```js +201 Created +``` + +```json +{ + "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "albums": [ + { + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "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.", + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { + "name": "Rock" + }, + { + "name": "Progressive Rock" + } + ], + "tags": [ + { + "name": "classic" + }, + { + "name": "vinyl" + } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "contributors": [ + { + "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", + "role": "Producer" + }, + { + "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", + "role": "Engineer" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + }, + { + "id": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ] + } + ] + } + ], + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null +} +``` + + +### Get Artists + +#### Get Artists Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1&perPage=10&searchTerm=queen +``` + +| Query Parameter | Type | Description | +| --- | --- | --- | +| `currentPage` | `int` | Optional. The page of results to retrieve. | +| `perPage` | `int` | Optional. The maximum number of artists to retrieve per page. | +| `searchTerm` | `string` | Optional. The search term used to filter the artists by name. | + +#### Get Artists Response + +```js +200 Ok +``` + +```json +{ + "data": [ + { + "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [], + "albums": [], + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null + } + ], + "currentPage": 1, + "perPage": 10, + "count": 1, + "numberOfPages": 1 +} +``` + + +### Get Artists Lite + +#### Get Artists Lite Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/lite?currentPage=1&perPage=10&searchTerm=queen +``` + +| Query Parameter | Type | Description | +| --- | --- | --- | +| `currentPage` | `int` | Optional. The page of results to retrieve. | +| `perPage` | `int` | Optional. The maximum number of artists to retrieve per page. | +| `searchTerm` | `string` | Optional. The search term used to filter the artists by name. | + +#### Get Artists Lite Response + +```js +200 Ok +``` + +```json +{ + "data": [ + { + "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "name": "Queen" + } + ], + "currentPage": 1, + "perPage": 10, + "count": 1, + "numberOfPages": 1 +} +``` + + +### Get Artist + +#### Get Artist Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} +``` + +#### Get Artist Response + +```js +200 Ok +``` + +```json +{ + "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "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 +} +``` + + +### Update Artist + +#### Update Artist Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} +``` + +```json +{ + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "albums": [ + { + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12 + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } + ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + }, + { + "trackId": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b", + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } + ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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" } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ] + } + ] + } + ] +} +``` + +#### Update Artist Response + +```js +200 Ok +``` + +```json +{ + "id": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "albums": [ + { + "id": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "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.", + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { + "name": "Rock" + }, + { + "name": "Progressive Rock" + } + ], + "tags": [ + { + "name": "classic" + }, + { + "name": "vinyl" + } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "contributors": [ + { + "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", + "role": "Producer" + }, + { + "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", + "role": "Engineer" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + }, + { + "id": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ] + } + ] + } + ], + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": "2025-02-01T12:00:00.0000000Z" +} +``` + + +### Delete Artist + +```js +DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} +``` + +```js +200 Ok +``` + +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 new file mode 100644 index 00000000..d578a1a1 --- /dev/null +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -0,0 +1,446 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Track](#track) + - [Add Track](#add-track) + - [Add Track Request](#add-track-request) + - [Add Track Response](#add-track-response) + - [Get Track](#get-track) + - [Get Track Request](#get-track-request) + - [Get Track Response](#get-track-response) + - [Update Track](#update-track) + - [Update Track Request](#update-track-request) + - [Update Track Response](#update-track-response) + - [Delete Track](#delete-track) + +## Track + +### Add Track + +#### Add Track Request + +```js +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +``` + +```json +{ + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ] + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} +``` + +#### Add Track Response + +```js +201 Created +``` + +```json +{ + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} +``` + + +### Get Track + +#### Get Track Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +``` + +#### Get Track Response + +```js +200 Ok +``` + +```json +{ + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} +``` + + +### Update Track + +#### Update Track Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +``` + +```json +{ + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ] + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} +``` + +#### Update Track Response + +```js +200 Ok +``` + +```json +{ + "id": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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", + "role": "Vocals" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Guitar" + } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} +``` + + +### Delete Track + +```js +DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{trackId} +``` + +```js +200 Ok +``` + +Deletes the track identified by the route. diff --git a/docs/technical/api/library-management/Api.Library.md b/docs/technical/api/library/management/Api.Libraries.md similarity index 100% rename from docs/technical/api/library-management/Api.Library.md rename to docs/technical/api/library/management/Api.Libraries.md diff --git a/docs/technical/api/Api.Book.md b/docs/technical/api/library/written-content-library/book-library/Api.Books.md similarity index 53% rename from docs/technical/api/Api.Book.md rename to docs/technical/api/library/written-content-library/book-library/Api.Books.md index b5709b2e..ef7a6afb 100644 --- a/docs/technical/api/Api.Book.md +++ b/docs/technical/api/library/written-content-library/book-library/Api.Books.md @@ -14,6 +14,12 @@ - [Get Books Lite](#get-books-lite) - [Get Books Lite Request](#get-books-lite-request) - [Get Books Lite Response](#get-books-lite-response) + - [Update Book](#update-book) + - [Update Book Request](#update-book-request) + - [Update Book Response](#update-book-response) + - [Update Book Cover](#update-book-cover) + - [Update Book Cover Request](#update-book-cover-request) + - [Update Book Cover Response](#update-book-cover-response) - [Get Reading Availability](#get-reading-availability) - [Get Reading Availability Request](#get-reading-availability-request) - [Get Reading Availability Response](#get-reading-availability-response) @@ -34,13 +40,12 @@ #### Add Book Request ```js -POST api/v1/books +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books ``` ```json { - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", "metadata": { "title": "The Fellowship of the Ring", "originalTitle": "The Fellowship of the Ring", @@ -50,7 +55,7 @@ POST api/v1/books "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "genres": [ @@ -93,33 +98,27 @@ POST api/v1/books "appleBooksId": "id395211", "isbns": [ { - "value": "0395272238", - "format": "Isbn10" + "value": "0395272238", + "format": "Isbn10" }, { - "value": "9780395272237", - "format": "Isbn13" + "value": "9780395272237", + "format": "Isbn13" } ], "contributors": [ { - "name": "J.R.R. Tolkien", - "role": { - "name": "author", - "category": "book" - } + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Author" }, { - "name": "Alan Lee", - "role": { - "name": "illustrator", - "category": "book" - } + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Illustrator" } ], "ratings": [ { - "source": "Goodreads", + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 @@ -144,7 +143,7 @@ POST api/v1/books { "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", "metadata": { "publisher": "Houghton Mifflin", "pageCount": 398, @@ -156,7 +155,7 @@ POST api/v1/books "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "language": { @@ -215,14 +214,19 @@ POST api/v1/books "format": "Isbn13" } ], - "contributors": [], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], "ratings": [ { + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 }, { + "source": "Amazon", "value": 4.7, "maxValue": 5, "voteCount": 87654 @@ -232,7 +236,8 @@ POST api/v1/books "lastMetadataUpdateUtc": null, "metadataProvider": null, "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + "updatedOnUtc": null, + "coverPath": null } ``` @@ -241,7 +246,7 @@ POST api/v1/books #### Get Book Request ```js -GET api/v1/books/{id} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} ``` #### Get Book Response @@ -250,19 +255,118 @@ GET api/v1/books/{id} 200 Ok ``` -Returns an empty response. This endpoint is not yet implemented. +```json +{ + "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", + "metadata": { + "publisher": "Houghton Mifflin", + "pageCount": 398, + "title": "The Fellowship of the Ring", + "originalTitle": "The Fellowship of the Ring", + "description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + "releaseInfo": { + "originalReleaseDate": "1954-07-29", + "originalReleaseYear": 1954, + "reReleaseDate": "2001-09-06", + "reReleaseYear": 2001, + "releaseCountry": "GB", + "releaseVersion": "50th Anniversary Edition" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { + "name": "epic fantasy" + }, + { + "name": "quest" + }, + { + "name": "middle-earth" + } + ], + "genres": [ + { + "name": "fantasy" + }, + { + "name": "adventure" + }, + { + "name": "classic" + } + ] + }, + "format": "Paperback", + "edition": "50th Anniversary Edition", + "volumeNumber": 1, + "series": null, + "asin": "B007978NPG", + "goodreadsId": "3", + "lccn": "54009621", + "oclcNumber": "ocm00012345", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], + "ratings": [ + { + "source": "GoogleBooks", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ], + "metadataStatus": "Pending", + "lastMetadataUpdateUtc": null, + "metadataProvider": null, + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": null, + "coverPath": null +} +``` ### Get Books #### Get Books Request ```js -GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending ``` | Query Parameter | Type | Description | | --- | --- | --- | -| `libraryId` | `string` (GUID) | Required. The Id of the media library whose books are retrieved. | | `currentPage` | `int` | Optional. The page of results to retrieve. | | `perPage` | `int` | Optional. The maximum number of books to retrieve per page. | | `searchTerm` | `string` | Optional. The search term used to filter results. | @@ -281,7 +385,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe { "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", "metadata": { "title": "The Fellowship of the Ring", "originalTitle": "The Fellowship of the Ring", @@ -291,7 +395,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "genres": [ @@ -320,9 +424,7 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe "format": "Paperback", "edition": "50th Anniversary Edition", "volumeNumber": 1, - "series": { - "title": "The Lord of the Rings" - }, + "series": null, "asin": "B007978NPG", "goodreadsId": "3", "lccn": "54009621", @@ -342,19 +444,30 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe "format": "Isbn13" } ], - "contributors": [], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], "ratings": [ { + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 } ], "metadataStatus": "Pending", "lastMetadataUpdateUtc": null, "metadataProvider": null, "createdOnUtc": "2025-01-01T12:00:00.0000000Z", - "updatedOnUtc": null + "updatedOnUtc": null, + "coverPath": null } ], "currentPage": 1, @@ -369,17 +482,16 @@ GET api/v1/books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&pe #### Get Books Lite Request ```js -GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&ignoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&shouldIgnoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending ``` | Query Parameter | Type | Description | | --- | --- | --- | -| `libraryId` | `string` (GUID) | Required. The Id of the media library whose books are retrieved. | | `currentPage` | `int` | Optional. The page of results to retrieve. | | `perPage` | `int` | Optional. The maximum number of books to retrieve per page. | | `searchTerm` | `string` | Optional. The search term used to filter results. | | `filterAlphaKey` | `string` | Optional. Filters results by the first character of their title. A single ASCII letter (case-insensitive), `#` for titles starting with a digit, or `*` for titles starting with any other character. | -| `ignoreThePrefixForAlphaPicker` | `bool` | Whether the leading "The " prefix of a title should be ignored when computing the alpha key. | +| `shouldIgnoreThePrefixForAlphaPicker` | `bool` | Whether the leading "The " prefix of a title should be ignored when computing the alpha key. | | `sortBy` | `string` | Optional. The name of the field by which to sort the results. | | `sortOrder` | `string` | Optional. The direction in which to sort the results (`Ascending` or `Descending`). | @@ -406,12 +518,247 @@ GET api/v1/books/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage } ``` +### Update Book + +#### Update Book Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId} +``` + +```json +{ + "metadata": { + "title": "The Fellowship of the Ring", + "originalTitle": "The Fellowship of the Ring", + "description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + "releaseInfo": { + "originalReleaseDate": "1954-07-29", + "originalReleaseYear": 1954, + "reReleaseDate": "2001-09-06", + "reReleaseYear": 2001, + "releaseCountry": "GB", + "releaseVersion": "50th Anniversary Edition" + }, + "genres": [ + { "name": "fantasy" }, + { "name": "adventure" }, + { "name": "classic" } + ], + "tags": [ + { "name": "epic fantasy" }, + { "name": "quest" }, + { "name": "middle-earth" } + ], + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "publisher": "Houghton Mifflin", + "pageCount": 398 + }, + "format": "Paperback", + "edition": "50th Anniversary Edition", + "volumeNumber": 1, + "series": { + "title": "The Lord of the Rings" + }, + "asin": "B007978NPG", + "goodreadsId": "3", + "lccn": "54009621", + "oclcNumber": "ocm00012345", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Author" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Illustrator" + } + ], + "ratings": [ + { + "source": "GoogleBooks", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ] +} +``` + +#### Update Book Response + +```js +200 Ok +``` + +```json +{ + "id": "32b336e8-dafc-4a08-9dec-9454e66dd55d", + "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", + "metadata": { + "publisher": "Houghton Mifflin", + "pageCount": 398, + "title": "The Fellowship of the Ring", + "originalTitle": "The Fellowship of the Ring", + "description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + "releaseInfo": { + "originalReleaseDate": "1954-07-29", + "originalReleaseYear": 1954, + "reReleaseDate": "2001-09-06", + "reReleaseYear": 2001, + "releaseCountry": "GB", + "releaseVersion": "50th Anniversary Edition" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { + "name": "epic fantasy" + }, + { + "name": "quest" + }, + { + "name": "middle-earth" + } + ], + "genres": [ + { + "name": "fantasy" + }, + { + "name": "adventure" + }, + { + "name": "classic" + } + ] + }, + "format": "Paperback", + "edition": "50th Anniversary Edition", + "volumeNumber": 1, + "series": null, + "asin": "B007978NPG", + "goodreadsId": "3", + "lccn": "54009621", + "oclcNumber": "ocm00012345", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Author" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Illustrator" } + ], + "ratings": [ + { + "source": "GoogleBooks", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ], + "metadataStatus": "Enriched", + "lastMetadataUpdateUtc": "2025-01-01T12:00:00.0000000Z", + "metadataProvider": "GoogleBooks", + "createdOnUtc": "2025-01-01T12:00:00.0000000Z", + "updatedOnUtc": "2025-02-01T12:00:00.0000000Z", + "coverPath": "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" +} +``` + +### Update Book Cover + +Updates the cover image of the book identified by `bookId` with the image uploaded in the multipart form of the request. The book must belong to the media library identified by `libraryId`, and the uploaded file must be an image. + +#### Update Book Cover Request + +```js +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/cover +Content-Type: multipart/form-data; boundary=LuminaBoundary + +--LuminaBoundary +Content-Disposition: form-data; name="cover"; filename="cover.jpg" +Content-Type: image/jpeg + +< ./cover.jpg +--LuminaBoundary-- +``` + +#### Update Book Cover Response + +```js +200 Ok +``` + +```json +{ + "coverPath": "/media/books/books-3f2504e0-4f89-41d3-9a0c-0305e82c3301/The Lord of the Rings-2b0e5f5a-0b3f-4b7e-8f4a-8c9e3d2f5a6b/cover.jpg" +} +``` + ### Get Reading Availability #### Get Reading Availability Request ```js -GET api/v1/books/{bookId}/reading/availability +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/availability ``` Reports whether the book identified by `bookId` can be opened for reading: the book reader that supports the format of the book is resolved and its enablement for the media library of the book is checked, without extracting the book. When the book cannot be read, the response carries the code of the error preventing it, so the client can tell a missing book reader apart from a disabled one. @@ -436,7 +783,7 @@ Reports whether the book identified by `bookId` can be opened for reading: the b #### Get Reading Manifest Request ```js -GET api/v1/books/{bookId}/reading/manifest +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/manifest ``` Opens the book identified by `bookId` for reading by extracting its contents through the book reader that is enabled for its media library, and returns the reading manifest: the title and author of the book, its hierarchical table of contents, its ordered spine of reading sections, the keys of its resources, and whether it has extractable text content. A scanned book, whose pages are only images, has no text content and is displayed as page images. @@ -487,7 +834,7 @@ Opens the book identified by `bookId` for reading by extracting its contents thr #### Get Reading Section Request ```js -GET api/v1/books/{bookId}/reading/sections/{locationRef} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/sections/{locationRef} ``` Returns the reading section identified by `locationRef` of the book identified by `bookId`. The section content is sanitized by the host before it is served, and its references to the resources of the book are resolved by the client through the resource endpoint. The `locationRef` of a section is taken from the spine of the reading manifest of the book. @@ -511,7 +858,7 @@ Returns the reading section identified by `locationRef` of the book identified b #### Get Reading Resource Request ```js -GET api/v1/books/{bookId}/reading/resources/{resourceKey} +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}/reading/resources/{resourceKey} ``` Returns the binary resource identified by `resourceKey` of the book identified by `bookId` (for example an image, a font, or a stylesheet of the book, or a page image of a scanned PDF that is rendered on demand). The `resourceKey` of a resource is taken from the reading manifest of the book. diff --git a/docs/technical/api/maintenance/Api.Health.md b/docs/technical/api/maintenance/Api.Health.md new file mode 100644 index 00000000..3014b35d --- /dev/null +++ b/docs/technical/api/maintenance/Api.Health.md @@ -0,0 +1,25 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Health](#health) + - [Check Health](#check-health) + - [Check Health Request](#check-health-request) + - [Check Health Response](#check-health-response) + +## Health + +### Check Health + +#### Check Health Request + +```js +GET api/v1/check-health +``` + +#### Check Health Response + +```js +200 Ok +``` + +Returns an empty response. This endpoint is not yet implemented. diff --git a/docs/technical/api/maintenance/Api.Maintenance.md b/docs/technical/api/maintenance/Api.Initialization.md similarity index 73% rename from docs/technical/api/maintenance/Api.Maintenance.md rename to docs/technical/api/maintenance/Api.Initialization.md index 6dbccd0f..bdb9a5cc 100644 --- a/docs/technical/api/maintenance/Api.Maintenance.md +++ b/docs/technical/api/maintenance/Api.Initialization.md @@ -1,10 +1,7 @@ # Lumina API - [Lumina API](#lumina-api) - - [Maintenance](#maintenance) - - [Check Health](#check-health) - - [Check Health Request](#check-health-request) - - [Check Health Response](#check-health-response) + - [Initialization](#initialization) - [Setup Application](#setup-application) - [Setup Application Request](#setup-application-request) - [Setup Application Response](#setup-application-response) @@ -12,23 +9,7 @@ - [Check Initialization Request](#check-initialization-request) - [Check Initialization Response](#check-initialization-response) -## Maintenance - -### Check Health - -#### Check Health Request - -```js -GET api/v1/check-health -``` - -#### Check Health Response - -```js -200 Ok -``` - -Returns an empty response. This endpoint is not yet implemented. +## Initialization ### Setup Application @@ -61,6 +42,7 @@ POST api/v1/initialization } ``` + ### Check Initialization #### Check Initialization Request @@ -79,4 +61,4 @@ GET api/v1/initialization { "isInitialized": true } -``` +``` \ No newline at end of file diff --git a/docs/technical/api/users-management/Api.Authorization.md b/docs/technical/api/users-management/Api.Authorization.md index abce3d67..6eb1f20f 100644 --- a/docs/technical/api/users-management/Api.Authorization.md +++ b/docs/technical/api/users-management/Api.Authorization.md @@ -2,24 +2,6 @@ - [Lumina API](#lumina-api) - [Authorization](#authorization) - - [Get Permissions](#get-permissions) - - [Get Permissions Request](#get-permissions-request) - - [Get Permissions Response](#get-permissions-response) - - [Get Roles](#get-roles) - - [Get Roles Request](#get-roles-request) - - [Get Roles Response](#get-roles-response) - - [Get Role Permissions](#get-role-permissions) - - [Get Role Permissions Request](#get-role-permissions-request) - - [Get Role Permissions Response](#get-role-permissions-response) - - [Add Role](#add-role) - - [Add Role Request](#add-role-request) - - [Add Role Response](#add-role-response) - - [Update Role](#update-role) - - [Update Role Request](#update-role-request) - - [Update Role Response](#update-role-response) - - [Delete Role](#delete-role) - - [Delete Role Request](#delete-role-request) - - [Delete Role Response](#delete-role-response) - [Get Authorization](#get-authorization) - [Get Authorization Request](#get-authorization-request) - [Get Authorization Response](#get-authorization-response) @@ -35,190 +17,6 @@ ## Authorization -### Get Permissions - -#### Get Permissions Request - -```js -GET api/v1/auth/permissions -``` - -#### Get Permissions Response - -```js -200 Ok -``` - -```json -[ - { - "id": "5264e3a8-bdec-4ec0-9423-839f3a9afe4b", - "permissionName": "CanDeleteUsers" - }, - { - "id": "7830cd55-3585-4da1-bfad-994be8637da8", - "permissionName": "CanViewUsers" - } -] -``` - -### Get Roles - -#### Get Roles Request - -```js -GET api/v1/auth/roles -``` - -#### Get Roles Response - -```js -200 Ok -``` - -```json -[ - { - "id": "776e440d-39d2-4f31-8dcd-481de61e8792", - "roleName": "Admin" - } -] -``` - -### Get Role Permissions - -#### Get Role Permissions Request - -```js -GET api/v1/auth/roles/{roleId}/permissions -``` - -#### Get Role Permissions Response - -```js -200 Ok -``` - -```json -{ - "role": { - "id": "61567253-c752-4680-989c-a40a73f3e4b9", - "roleName": "Editor" - }, - "permissions": [ - { - "id": "5264e3a8-bdec-4ec0-9423-839f3a9afe4b", - "permissionName": "CanDeleteUsers" - }, - { - "id": "7830cd55-3585-4da1-bfad-994be8637da8", - "permissionName": "CanViewUsers" - } - ] -} -``` - -### Add Role - -#### Add Role Request - -```js -POST api/v1/auth/roles -``` - -```json -{ - "roleName": "Editor", - "permissions": [ - "7934ff13-1ccd-4c24-bab3-6423c905e249", - "8f23e43a-bb4b-483a-99eb-7ab361df7482" - ] -} -``` - -#### Add Role Response - -```js -200 Ok -``` - -```json -{ - "role": { - "id": "e5b67972-6928-4be1-a757-e98879d4a12a", - "roleName": "Editor" - }, - "permissions": [ - { - "id": "7934ff13-1ccd-4c24-bab3-6423c905e249", - "permissionName": "CanDeleteUsers" - }, - { - "id": "8f23e43a-bb4b-483a-99eb-7ab361df7482", - "permissionName": "CanViewUsers" - } - ] -} -``` - -### Update Role - -#### Update Role Request - -```js -PUT api/v1/auth/roles -``` - -```json -{ - "roleId": "73d204e2-5922-441d-83d8-8d4d8fc29eaa", - "roleName": "Editor", - "permissions": [ - "ac113d18-69bb-4162-8c05-ff7a5559059a", - "3c2fd936-8d4a-4963-b237-9f8d3aeeab26" - ] -} -``` - -#### Update Role Response - -```js -200 Ok -``` - -```json -{ - "role": { - "id": "61567253-c752-4680-989c-a40a73f3e4b9", - "roleName": "Editor" - }, - "permissions": [ - { - "id": "5264e3a8-bdec-4ec0-9423-839f3a9afe4b", - "permissionName": "CanDeleteUsers" - }, - { - "id": "7830cd55-3585-4da1-bfad-994be8637da8", - "permissionName": "CanViewUsers" - } - ] -} -``` - -### Delete Role - -#### Delete Role Request - -```js -DELETE api/v1/auth/roles/{roleId} -``` - -#### Delete Role Response - -```js -204 No Content -``` - ### Get Authorization #### Get Authorization Request @@ -244,6 +42,7 @@ GET api/v1/auth/get-authorization?userId=8e5e2be7-9f3b-4309-882b-8913dc6bda10 } ``` + ### Get User Permissions #### Get User Permissions Request @@ -275,6 +74,7 @@ GET api/v1/auth/users/{userId}/permissions ] ``` + ### Get User Role #### Get User Role Request @@ -296,6 +96,7 @@ GET api/v1/auth/users/{userId}/role } ``` + ### Update User Role And Permissions #### Update User Role And Permissions Request @@ -329,4 +130,4 @@ PUT api/v1/auth/users/{userId}/role-and-permissions "CanDeleteUsers" ] } -``` +``` \ No newline at end of file diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md new file mode 100644 index 00000000..46b8df6e --- /dev/null +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md @@ -0,0 +1,84 @@ +# Architecture Decision Record (ADR): 0014 - Closed Generic Persistence Toolkit for Aggregate Graph Persistence + +## Status + +**Accepted** (2026-09-26) + +## Context + +Repositories in the DataAccess layer persist aggregate graphs: they load a tracked root entity, apply the edited scalar values, reconcile child collections, and add or update shared reference rows. This work was implemented independently in each repository, which produced duplication and drift. + +1. **Shared reference handling**: a shared reference row (a tag or a genre) is keyed by its name and is shared across the whole database. When a graph is inserted or updated, the stored rows whose names already exist have to be reused instead of re-inserted, so that the shared tables are not duplicated, and a name shared by several parents of one request must be tracked only once. This logic existed inline in `BookRepository`, and as a private `ReconcileTagsAndGenresAsync` method in `BookRepository`, `AlbumRepository`, and `TrackRepository`. + +2. **Child collection reconciliation**: the same identity-preserving reconcile logic was repeated for every child collection of every aggregate (contributors, ratings, ISBNs, tags, genres, moods, ISRCs, content locations, permissions). + +3. **Scalar copy on edit**: `EditableValuesCopier` applies editable scalar values while leaving the audit columns to the auditing interceptor. Seven auditable repositories (`Role`, `LibraryScan`, `ScheduledJob`, `ScheduledJobExecution`, `Theme`, `User`, `UserSettings`) still copied scalars with `CurrentValues.SetValues`, which writes every scalar property, including the primary key and the audit columns. Writing the primary key is destructive whenever the tracked row was located by a key other than its primary key: `UserRepository` locates the row by username, so an incoming entity whose Id differs from, or is unset relative to, the stored one would retarget the tracked row's identity, leaving the guarantee "the stored identity is never overwritten by an edit" to caller convention instead of to the code. + +`Lumina.DataAccess\Common\Persistence` already held `CollectionReconciler` and `EditableValuesCopier`, but there was no shared reference primitive and no explicit boundary defining what may live there, so the shared reference concern was expressed per type and per repository. + +## Decision + +Treat `Lumina.DataAccess\Common\Persistence` as a closed set of generic, entity-agnostic primitives that express the whole of aggregate graph persistence. Per-entity logic stays in the repository, and cross-cutting logic is generalized rather than specialized. + +### The closed set + +| Primitive | Responsibility | +|---|---| +| `EditableValuesCopier` | Copies only the editable scalar values onto the tracked entity. The primary key is never written, so the tracked identity always wins over the incoming one regardless of how the row was located, and the audit columns are never written, so the auditing interceptor remains their only writer. | +| `CollectionReconciler` | Reconciles a tracked child collection against a desired set by key selectors, preserving the identity and audit columns of the children that already exist. | +| `SharedReferenceResolver` | Resolves shared reference rows by name so each distinct name maps to a single tracked instance. The stored row wins over the incoming instance, and within-request duplicates are collapsed. | + +### Genericity rules + +- `EditableValuesCopier` is generic over `IAuditableEntity`. It reads the primary key from the Entity Framework metadata, so it enforces the key-matching contract for any entity without per-entity code. +- `CollectionReconciler` is generic over existing item, incoming item, and key type. +- `SharedReferenceResolver` is generic over `ISharedReferenceEntity`, a marker interface implemented by the shared reference records (`TagEntity`, `GenreEntity`). This is the one concern that is shaped by a family of entities, expressed through the marker interface rather than through per-entity code, so a new shared reference type adds no new persistence type. + +### Application + +- Insert resolves shared references across the whole aggregate, then normalizes every collection of the aggregate to the resolved instances. +- Update reconciles the tracked shared reference collections in place, reusing the stored rows. +- Scalar edits go through `EditableValuesCopier`. The repository decides how the tracked row is located (by its primary key, or by a natural key such as the username), and the copier keeps that row's primary key and audit columns untouched, so the incoming entity never has to carry a matching key. +- Child collections are reconciled through `CollectionReconciler` by a stable key. + +## Consequences + +### Positive Outcomes + +| Aspect | Benefit | +|---|---| +| Bounded surface | The folder holds exactly three generic types; new entity types and new shared reference types add no persistence type | +| Consistency | Every repository persists graphs the same way, with the same identity and audit semantics | +| Correctness | Audit columns are never overwritten by an edit, and shared reference rows are never tracked more than once per request | +| Identity preservation | The tracked primary key is never overwritten by an edit, even when the incoming entity carries a different, or unset, key, so locating a row by a natural key stays safe | +| Testability | The primitives are covered directly by unit tests, independently of any repository | +| Ownership | No new external dependency and no declarative engine; the toolkit depends only on the internal `ISharedReferenceEntity` marker, and the logic stays explicit and inspectable | + +### Risks and Mitigations + +| Risk | Mitigation Strategy | +|---|---| +| The generic resolver depends on an entity keyed by `Name` and translated by EF Core | `SharedReferenceResolver` is generic over `ISharedReferenceEntity` and is exercised by both unit and integration tests, which prove the EF translation | +| A future concern is generalized before its shape is stable | The rule permits keeping a concern in the repository until it can actually be generalized, rather than extracting speculatively | +| Behavior change from applying `EditableValuesCopier` to the seven repositories | Covered by the DataAccess and Presentation.Api integration suites, which pass across the migrated repositories | +| The copier relies on Entity Framework metadata to find the primary key | Unit tests copy onto a tracked entity whose incoming key does not match, and assert that the stored identity and audit columns survive | + +## Alternatives Considered + +### 1. Keep graph persistence duplicated in each repository + +Leave the shared reference handling, collection reconciliation, and scalar copy implemented per repository. + +**Rejected**: the duplication and the drift are the problem this decision addresses. Shared reference handling in particular has a single general shape, and repeating it per repository is what allows the shared-table and audit-column defects above to reappear. + +### 2. Declarative aggregate persistence profiles + +Introduce a generic persistence engine driven by a per-aggregate profile describing scalar copy behavior, child collections, and shared lookups, reducing repositories to load and apply. + +**Rejected**: it is effectively a small in-house ORM, with functional and ownership costs disproportionate to the problem. The closed generic toolkit achieves the stated goal, keeping graph persistence explicit, without a new abstraction layer to own. + +### 3. Model tags and genres as owned value objects + +Stop modeling shared references as a shared table keyed by name, and store them per aggregate, removing the duplicate-key-in-graph class of bug at the source. + +**Rejected**: it requires a database schema change and changes query behavior for shared references, which is out of scope. The shared tables are kept, and the concern is handled where it belongs, in the persistence toolkit. diff --git a/docs/technical/domain/Aggregates.AudioLibrary.md b/docs/technical/domain/Aggregates.AudioLibrary.md new file mode 100644 index 00000000..08a4c673 --- /dev/null +++ b/docs/technical/domain/Aggregates.AudioLibrary.md @@ -0,0 +1,251 @@ +- [Lumina Domain](#lumina-domain) + - [Audio Library Aggregate](#audio-library-aggregate) + - [Artist](#artist) + - [Album](#album) + - [Track](#track) + +# [Lumina Domain](#lumina-domain) + +## [Audio Library Aggregate](#audio-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. + +### [Artist](#artist) + +```csharp +class Artist +{ + Result Create( + LibraryId libraryId, + string name, + Optional website, + Optional musicBrainzArtistId, + List contributors, + List albums); +} +``` + +```json +{ + "id": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "libraryId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "contributors": [], + "albums": [ + { + "value": "00000000-0000-0000-0000-000000000000" + } + ] +} +``` + +### [Album](#album) + +```csharp +class Album +{ + Result Create( + AlbumMetadata metadata, + Optional mediaFormat, + Optional barcode, + Optional catalogNumber, + Optional musicBrainzReleaseId, + Optional musicBrainzReleaseGroupId, + Optional musicBrainzReleaseArtistId, + List contributors, + List ratings, + List tracks); +} +``` + +```json +{ + "id": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12 + }, + "mediaFormat": "CD", + "barcode": { + "value": "0042282778329" + }, + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "musicBrainzReleaseGroupId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "musicBrainzReleaseArtistId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "contributors": [], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "value": "00000000-0000-0000-0000-000000000000" + } + ] +} +``` + +### [Track](#track) + +```csharp +class Track +{ + Result Create( + LibraryId libraryId, + string path, + AudioMetadata metadata, + int trackNumber, + Optional discNumber, + List isrcs, + Optional script, + Optional key, + Optional bpm, + List moods, + Optional work, + Optional musicBrainzRecordingId, + Optional musicBrainzTrackId, + Optional musicBrainzWorkId, + List contributors, + List ratings); +} +``` + +```json +{ + "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", + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ], + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "isrcs": [ + { + "value": "GBUM71029604" + } + ], + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "moods": [ + { "name": "dramatic" }, + { "name": "anxious" } + ], + "work": "Bohemian Rhapsody", + "musicBrainzRecordingId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "musicBrainzTrackId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "musicBrainzWorkId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "contributors": [], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + } + ] +} +``` diff --git a/docs/technical/domain/Aggregates.WrittenContentLibrary.md b/docs/technical/domain/Aggregates.WrittenContentLibrary.md index 19bac436..9c629327 100644 --- a/docs/technical/domain/Aggregates.WrittenContentLibrary.md +++ b/docs/technical/domain/Aggregates.WrittenContentLibrary.md @@ -27,7 +27,7 @@ class Book Optional barnesAndNobleId, Optional appleBooksId, List isbns, - List contributors, + List contributors, List ratings); } ``` @@ -46,7 +46,7 @@ class Book "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "genres": [ @@ -99,7 +99,10 @@ class Book ], "contributors": [ { - "value": "00000000-0000-0000-0000-000000000000", + "contributorId": { + "value": "00000000-0000-0000-0000-000000000000" + }, + "role": "Author" } ], "ratings": [ diff --git a/docs/technical/domain/Common.Metadata.md b/docs/technical/domain/Common.Metadata.md index 8b6e4a3c..967e86d9 100644 --- a/docs/technical/domain/Common.Metadata.md +++ b/docs/technical/domain/Common.Metadata.md @@ -87,7 +87,7 @@ class ReleaseInfo ```csharp class LanguageInfo { - ErrorOr Create(string languageCode, string languageName, Optional nativeName); + LanguageInfo Create(string languageCode, string languageName, Optional nativeName); } ``` diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index cf31fb0a..4f3d9024 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -10,6 +10,7 @@ - _**File**_: The actual digital file of a media item - _**Stream**_: A media item accessed via streaming rather than local storage - _**Language Track**_: An audio or text track in a specific language +- _**Media Contributor**_: A person, group, or organization that contributed to a media item, together with the role they played ## Video Content - _**TV Show**_: A series of episodes typically organized into seasons @@ -113,6 +114,7 @@ - File - Stream - LanguageTrack +- MediaContributor ## Aggregates - VideoLibrary (root: VideoLibrary, entities: TVShow, Season, Episode, Movie, FilmSeries, ConcertVideo, Documentary, TutorialVideo, HomeVideo, Anime, YouTubeVideo, MusicVideo) diff --git a/docs/technical/requests/users-management/authorization/GetPermissions.http b/docs/technical/requests/admin/authorization/permissions/GetPermissions.http similarity index 100% rename from docs/technical/requests/users-management/authorization/GetPermissions.http rename to docs/technical/requests/admin/authorization/permissions/GetPermissions.http diff --git a/docs/technical/requests/users-management/authorization/AddRole.http b/docs/technical/requests/admin/authorization/roles/AddRole.http similarity index 100% rename from docs/technical/requests/users-management/authorization/AddRole.http rename to docs/technical/requests/admin/authorization/roles/AddRole.http diff --git a/docs/technical/requests/users-management/authorization/DeleteRole.http b/docs/technical/requests/admin/authorization/roles/DeleteRole.http similarity index 100% rename from docs/technical/requests/users-management/authorization/DeleteRole.http rename to docs/technical/requests/admin/authorization/roles/DeleteRole.http diff --git a/docs/technical/requests/users-management/authorization/GetRolePermissions.http b/docs/technical/requests/admin/authorization/roles/GetRolePermissions.http similarity index 100% rename from docs/technical/requests/users-management/authorization/GetRolePermissions.http rename to docs/technical/requests/admin/authorization/roles/GetRolePermissions.http diff --git a/docs/technical/requests/users-management/authorization/GetRoles.http b/docs/technical/requests/admin/authorization/roles/GetRoles.http similarity index 100% rename from docs/technical/requests/users-management/authorization/GetRoles.http rename to docs/technical/requests/admin/authorization/roles/GetRoles.http diff --git a/docs/technical/requests/users-management/authorization/UpdateRole.http b/docs/technical/requests/admin/authorization/roles/UpdateRole.http similarity index 100% rename from docs/technical/requests/users-management/authorization/UpdateRole.http rename to docs/technical/requests/admin/authorization/roles/UpdateRole.http diff --git a/docs/technical/requests/books/GetAll.http b/docs/technical/requests/books/GetAll.http deleted file mode 100644 index f8d5d229..00000000 --- a/docs/technical/requests/books/GetAll.http +++ /dev/null @@ -1 +0,0 @@ -GET {{host}}/api/v1/books?libraryId={{$guid}} \ No newline at end of file diff --git a/docs/technical/requests/books/GetBooksLite.http b/docs/technical/requests/books/GetBooksLite.http deleted file mode 100644 index 609dbb6f..00000000 --- a/docs/technical/requests/books/GetBooksLite.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/books/lite?libraryId={{$guid}}¤tPage=1&perPage=10 -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetById.http b/docs/technical/requests/books/GetById.http deleted file mode 100644 index b2c5f4e7..00000000 --- a/docs/technical/requests/books/GetById.http +++ /dev/null @@ -1 +0,0 @@ -GET {{host}}/api/v1/books/{{$guid}} diff --git a/docs/technical/requests/books/GetReadingAvailability.http b/docs/technical/requests/books/GetReadingAvailability.http deleted file mode 100644 index e5dcdb0e..00000000 --- a/docs/technical/requests/books/GetReadingAvailability.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/availability -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetReadingManifest.http b/docs/technical/requests/books/GetReadingManifest.http deleted file mode 100644 index c5d92cab..00000000 --- a/docs/technical/requests/books/GetReadingManifest.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/manifest -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetReadingResource.http b/docs/technical/requests/books/GetReadingResource.http deleted file mode 100644 index 8133bb5b..00000000 --- a/docs/technical/requests/books/GetReadingResource.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/resources/0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/GetReadingSection.http b/docs/technical/requests/books/GetReadingSection.http deleted file mode 100644 index 1b382784..00000000 --- a/docs/technical/requests/books/GetReadingSection.http +++ /dev/null @@ -1,2 +0,0 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/sections/chapter1 -Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/file-system-management/directories/GetDirectories.http b/docs/technical/requests/file-system-management/directories/GetDirectories.http index e915ad5a..6023595c 100644 --- a/docs/technical/requests/file-system-management/directories/GetDirectories.http +++ b/docs/technical/requests/file-system-management/directories/GetDirectories.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/directories/get-directories?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET {{host}}/api/v1/directories/get-directories?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/file-system-management/files/GetFiles.http b/docs/technical/requests/file-system-management/files/GetFiles.http index 7f81bff0..74987a51 100644 --- a/docs/technical/requests/file-system-management/files/GetFiles.http +++ b/docs/technical/requests/file-system-management/files/GetFiles.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/files/get-files?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET {{host}}/api/v1/files/get-files?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/file-system-management/files/GetTreeFiles.http b/docs/technical/requests/file-system-management/files/GetTreeFiles.http index 727d0571..f072c653 100644 --- a/docs/technical/requests/file-system-management/files/GetTreeFiles.http +++ b/docs/technical/requests/file-system-management/files/GetTreeFiles.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/files/get-tree-files?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET {{host}}/api/v1/files/get-tree-files?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/file-system-management/path/CheckPathExists.http b/docs/technical/requests/file-system-management/path/CheckPathExists.http index 281525ce..11d1ea50 100644 --- a/docs/technical/requests/file-system-management/path/CheckPathExists.http +++ b/docs/technical/requests/file-system-management/path/CheckPathExists.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/path/check-path-exists?path=C%3A%5CUsers%5C&includeHiddenElements=true +GET {{host}}/api/v1/path/check-path-exists?path=C%3A%5CUsers%5C&shouldIncludeHiddenElements=true Authorization: Bearer {{ACCESS_TOKEN}} 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 new file mode 100644 index 00000000..1f173f5b --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http @@ -0,0 +1,215 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ] + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", + "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", + "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "moods": [ + { "name": "dramatic" }, + { "name": "anxious" } + ], + "isrcs": [ + { "value": "GBUM71029604" } + ] + }, + { + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Pop Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "love" } + ] + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", + "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ], + "moods": [ + { "name": "happy" }, + { "name": "warm" } + ], + "isrcs": [ + { "value": "GBUM71029609" } + ] + } + ] +} diff --git a/docs/technical/requests/library/audio-library/music-library/albums/DeleteAlbum.http b/docs/technical/requests/library/audio-library/music-library/albums/DeleteAlbum.http new file mode 100644 index 00000000..fcb6dc9a --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/DeleteAlbum.http @@ -0,0 +1,2 @@ +DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/albums/GetAlbum.http b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbum.http new file mode 100644 index 00000000..c15bbe79 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbum.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracks.http b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracks.http new file mode 100644 index 00000000..0ac09042 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracks.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}}/tracks +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracksLite.http b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracksLite.http new file mode 100644 index 00000000..51a5f3b4 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracksLite.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}}/tracks/lite?currentPage=1&perPage=10 +Authorization: Bearer {{ACCESS_TOKEN}} 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 new file mode 100644 index 00000000..53a701cd --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http @@ -0,0 +1,65 @@ +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ] + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} 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 new file mode 100644 index 00000000..56cba33b --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http @@ -0,0 +1,226 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12 + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } + ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + }, + { + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } + ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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" } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ] + } + ] + } + ] +} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/DeleteArtist.http b/docs/technical/requests/library/audio-library/music-library/artists/DeleteArtist.http new file mode 100644 index 00000000..47c6f62d --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/DeleteArtist.http @@ -0,0 +1,2 @@ +DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/GetArtist.http b/docs/technical/requests/library/audio-library/music-library/artists/GetArtist.http new file mode 100644 index 00000000..2a56cc5d --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtist.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbums.http b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbums.http new file mode 100644 index 00000000..1d887e85 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbums.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/albums +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbumsLite.http b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbumsLite.http new file mode 100644 index 00000000..31325b3e --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbumsLite.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}}/albums/lite?currentPage=1&perPage=10 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/GetArtists.http b/docs/technical/requests/library/audio-library/music-library/artists/GetArtists.http new file mode 100644 index 00000000..0b41f86b --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtists.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1&perPage=10&searchTerm=queen +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/artists/GetArtistsLite.http b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistsLite.http new file mode 100644 index 00000000..c95805e1 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistsLite.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/lite?currentPage=1&perPage=10&searchTerm=queen +Authorization: Bearer {{ACCESS_TOKEN}} 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 new file mode 100644 index 00000000..23ddb7ec --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http @@ -0,0 +1,229 @@ +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "name": "Queen", + "website": "https://www.queenonline.com", + "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [ + { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, + { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } + ], + "albums": [ + { + "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", + "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.", + "releaseInfo": { + "originalReleaseDate": "1975-11-21", + "originalReleaseYear": 1975, + "reReleaseDate": null, + "reReleaseYear": null, + "releaseCountry": "GB", + "releaseVersion": "Remastered" + }, + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "tags": [ + { "name": "classic" }, + { "name": "vinyl" } + ], + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "releaseType": "Album", + "releaseStatus": "Official", + "totalDiscs": 1, + "totalTracks": 12 + }, + "mediaFormat": "CD", + "barcode": "0042282778329", + "catalogNumber": "EMC 4008", + "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", + "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", + "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", + "contributors": [ + { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, + { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ], + "tracks": [ + { + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "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" } + ], + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980 + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] + }, + { + "trackId": "8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b", + "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + "metadata": { + "title": "You're My Best Friend", + "originalTitle": "You're My Best Friend", + "description": "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + "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" } + ], + "durationInSeconds": 181, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 912 + }, + "trackNumber": 7, + "discNumber": 1, + "script": "Latn", + "key": "BMajor", + "bpm": 118, + "work": "You're My Best Friend", + "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" } + ], + "ratings": [ + { + "value": 4.2, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 1234 + }, + { + "value": 4.4, + "maxValue": 5, + "source": "LastFm", + "voteCount": 567 + } + ] + } + ] + } + ] +} 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 new file mode 100644 index 00000000..2bbfabe7 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http @@ -0,0 +1,78 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ] + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/DeleteTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/DeleteTrack.http new file mode 100644 index 00000000..786e65c0 --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/DeleteTrack.http @@ -0,0 +1,2 @@ +DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/GetTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/GetTrack.http new file mode 100644 index 00000000..ec1ae67c --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/GetTrack.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} 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 new file mode 100644 index 00000000..f7ae653d --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http @@ -0,0 +1,78 @@ +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + "metadata": { + "title": "Bohemian Rhapsody", + "originalTitle": "Bohemian Rhapsody", + "description": "A song by the British rock band Queen. It was written by Freddie Mercury and originally released on the album A Night at the Opera in 1975.", + "durationInSeconds": 354, + "sampleRate": 44100, + "channels": 2, + "bitDepth": 16, + "audioCodec": "FLAC", + "bitrate": 980, + "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" + }, + "genres": [ + { "name": "Rock" }, + { "name": "Progressive Rock" } + ], + "tags": [ + { "name": "classic" }, + { "name": "epic" } + ] + }, + "trackNumber": 1, + "discNumber": 1, + "script": "Latn", + "key": "CMajor", + "bpm": 72, + "work": "Bohemian Rhapsody", + "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" } + ], + "ratings": [ + { + "value": 4.5, + "maxValue": 5, + "source": "MusicBrainz", + "voteCount": 2345 + }, + { + "value": 4.8, + "maxValue": 5, + "source": "LastFm", + "voteCount": 1234 + } + ] +} diff --git a/docs/technical/requests/library-management/AddLibrary.http b/docs/technical/requests/library/management/AddLibrary.http similarity index 100% rename from docs/technical/requests/library-management/AddLibrary.http rename to docs/technical/requests/library/management/AddLibrary.http diff --git a/docs/technical/requests/library-management/CancelLibrariesScan.http b/docs/technical/requests/library/management/CancelLibrariesScan.http similarity index 100% rename from docs/technical/requests/library-management/CancelLibrariesScan.http rename to docs/technical/requests/library/management/CancelLibrariesScan.http diff --git a/docs/technical/requests/library-management/CancelLibraryScan.http b/docs/technical/requests/library/management/CancelLibraryScan.http similarity index 100% rename from docs/technical/requests/library-management/CancelLibraryScan.http rename to docs/technical/requests/library/management/CancelLibraryScan.http diff --git a/docs/technical/requests/library-management/DeleteLibrary.http b/docs/technical/requests/library/management/DeleteLibrary.http similarity index 100% rename from docs/technical/requests/library-management/DeleteLibrary.http rename to docs/technical/requests/library/management/DeleteLibrary.http diff --git a/docs/technical/requests/library-management/GetEnabledLibraries.http b/docs/technical/requests/library/management/GetEnabledLibraries.http similarity index 100% rename from docs/technical/requests/library-management/GetEnabledLibraries.http rename to docs/technical/requests/library/management/GetEnabledLibraries.http diff --git a/docs/technical/requests/library-management/GetLibraries.http b/docs/technical/requests/library/management/GetLibraries.http similarity index 100% rename from docs/technical/requests/library-management/GetLibraries.http rename to docs/technical/requests/library/management/GetLibraries.http diff --git a/docs/technical/requests/library-management/GetLibrary.http b/docs/technical/requests/library/management/GetLibrary.http similarity index 100% rename from docs/technical/requests/library-management/GetLibrary.http rename to docs/technical/requests/library/management/GetLibrary.http diff --git a/docs/technical/requests/library-management/GetLibraryScanProgress.http b/docs/technical/requests/library/management/GetLibraryScanProgress.http similarity index 100% rename from docs/technical/requests/library-management/GetLibraryScanProgress.http rename to docs/technical/requests/library/management/GetLibraryScanProgress.http diff --git a/docs/technical/requests/library-management/GetRunningLibraryScans.http b/docs/technical/requests/library/management/GetRunningLibraryScans.http similarity index 100% rename from docs/technical/requests/library-management/GetRunningLibraryScans.http rename to docs/technical/requests/library/management/GetRunningLibraryScans.http diff --git a/docs/technical/requests/library-management/ScanLibraries.http b/docs/technical/requests/library/management/ScanLibraries.http similarity index 100% rename from docs/technical/requests/library-management/ScanLibraries.http rename to docs/technical/requests/library/management/ScanLibraries.http diff --git a/docs/technical/requests/library-management/ScanLibrary.http b/docs/technical/requests/library/management/ScanLibrary.http similarity index 100% rename from docs/technical/requests/library-management/ScanLibrary.http rename to docs/technical/requests/library/management/ScanLibrary.http diff --git a/docs/technical/requests/library-management/UpdateLibrary.http b/docs/technical/requests/library/management/UpdateLibrary.http similarity index 100% rename from docs/technical/requests/library-management/UpdateLibrary.http rename to docs/technical/requests/library/management/UpdateLibrary.http diff --git a/docs/technical/requests/library/written-content-library/book-library/books/AddBook.http b/docs/technical/requests/library/written-content-library/book-library/books/AddBook.http new file mode 100644 index 00000000..3d915466 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/AddBook.http @@ -0,0 +1,91 @@ +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "path": "/media/libraries/books/the-fellowship-of-the-ring.pdf", + "metadata": { + "title": "The Fellowship of the Ring", + "originalTitle": "The Fellowship of the Ring", + "description": "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", + "releaseInfo": { + "originalReleaseDate": "1954-07-29", + "originalReleaseYear": 1954, + "reReleaseDate": "2001-09-06", + "reReleaseYear": 2001, + "releaseCountry": "GB", + "releaseVersion": "50th Anniversary Edition" + }, + "genres": [ + { "name": "fantasy" }, + { "name": "adventure" }, + { "name": "classic" } + ], + "tags": [ + { "name": "epic fantasy" }, + { "name": "quest" }, + { "name": "middle-earth" } + ], + "language": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "originalLanguage": { + "languageCode": "en", + "languageName": "English", + "nativeName": "English" + }, + "publisher": "Houghton Mifflin", + "pageCount": 398 + }, + "format": "Paperback", + "edition": "50th Anniversary Edition", + "volumeNumber": 1, + "series": { + "title": "The Lord of the Rings" + }, + "asin": "B007978NPG", + "goodreadsId": "3", + "lccn": "54009621", + "oclcNumber": "ocm00012345", + "openLibraryId": "OL7603910M", + "libraryThingId": "3203347", + "googleBooksId": "aWZzLPhY4o0C", + "barnesAndNobleId": "1100307790", + "appleBooksId": "id395211", + "isbns": [ + { + "value": "0395272238", + "format": "Isbn10" + }, + { + "value": "9780395272237", + "format": "Isbn13" + } + ], + "contributors": [ + { + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Author" + }, + { + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Illustrator" + } + ], + "ratings": [ + { + "source": "GoogleBooks", + "value": 4.36, + "maxValue": 5, + "voteCount": 2345678 + }, + { + "source": "Amazon", + "value": 4.7, + "maxValue": 5, + "voteCount": 87654 + } + ] +} \ No newline at end of file diff --git a/docs/technical/requests/library/written-content-library/book-library/books/GetBook.http b/docs/technical/requests/library/written-content-library/book-library/books/GetBook.http new file mode 100644 index 00000000..4f88eaa8 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/GetBook.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http b/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http new file mode 100644 index 00000000..48920207 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/GetBooks.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books?currentPage=1&perPage=10&searchTerm=fellowship&sortBy=title&sortOrder=Ascending +Authorization: Bearer {{ACCESS_TOKEN}} \ No newline at end of file diff --git a/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http b/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http new file mode 100644 index 00000000..7f67672b --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/GetBooksLite.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite?currentPage=1&perPage=10&searchTerm=fellowship&filterAlphaKey=f&shouldIgnoreThePrefixForAlphaPicker=true&sortBy=title&sortOrder=Ascending +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/books/Add.http b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http similarity index 79% rename from docs/technical/requests/books/Add.http rename to docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http index 8afe7f01..ea851263 100644 --- a/docs/technical/requests/books/Add.http +++ b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBook.http @@ -1,9 +1,8 @@ -POST {{host}}/api/v1/books +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", - "path": "/books/the-fellowship-of-the-ring.pdf", "metadata": { "title": "The Fellowship of the Ring", "originalTitle": "The Fellowship of the Ring", @@ -13,7 +12,7 @@ Content-Type: application/json "originalReleaseYear": 1954, "reReleaseDate": "2001-09-06", "reReleaseYear": 2001, - "releaseCountry": "uk", + "releaseCountry": "GB", "releaseVersion": "50th Anniversary Edition" }, "genres": [ @@ -56,33 +55,27 @@ Content-Type: application/json "appleBooksId": "id395211", "isbns": [ { - "value": "0395272238", - "format": "Isbn10" + "value": "0395272238", + "format": "Isbn10" }, { - "value": "9780395272237", - "format": "Isbn13" + "value": "9780395272237", + "format": "Isbn13" } ], "contributors": [ { - "name": "J.R.R. Tolkien", - "role": { - "name": "author", - "category": "book" - } + "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", + "role": "Author" }, { - "name": "Alan Lee", - "role": { - "name": "illustrator", - "category": "book" - } + "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", + "role": "Illustrator" } ], "ratings": [ { - "source": "Goodreads", + "source": "GoogleBooks", "value": 4.36, "maxValue": 5, "voteCount": 2345678 @@ -94,4 +87,4 @@ Content-Type: application/json "voteCount": 87654 } ] -} \ No newline at end of file +} diff --git a/docs/technical/requests/library/written-content-library/book-library/books/UpdateBookCover.http b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBookCover.http new file mode 100644 index 00000000..3762accb --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBookCover.http @@ -0,0 +1,10 @@ +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/cover +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: multipart/form-data; boundary=LuminaBoundary + +--LuminaBoundary +Content-Disposition: form-data; name="cover"; filename="cover.jpg" +Content-Type: image/jpeg + +< ./cover.jpg +--LuminaBoundary-- diff --git a/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingAvailability.http b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingAvailability.http new file mode 100644 index 00000000..60325776 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingAvailability.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/reading/availability +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingManifest.http b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingManifest.http new file mode 100644 index 00000000..7a8ad10a --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingManifest.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/reading/manifest +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingResource.http b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingResource.http new file mode 100644 index 00000000..c48a27b7 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingResource.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/reading/resources/0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingSection.http b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingSection.http new file mode 100644 index 00000000..381cede6 --- /dev/null +++ b/docs/technical/requests/library/written-content-library/book-library/books/reading/GetReadingSection.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/reading/sections/chapter1 +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/maintenance/CheckInitialization.http b/docs/technical/requests/maintenance/application-setup/CheckInitialization.http similarity index 100% rename from docs/technical/requests/maintenance/CheckInitialization.http rename to docs/technical/requests/maintenance/application-setup/CheckInitialization.http diff --git a/docs/technical/requests/maintenance/SetupApplication.http b/docs/technical/requests/maintenance/application-setup/SetupApplication.http similarity index 100% rename from docs/technical/requests/maintenance/SetupApplication.http rename to docs/technical/requests/maintenance/application-setup/SetupApplication.http diff --git a/docs/technical/requests/plugins/GetLibraryArtworkProviders.http b/docs/technical/requests/plugins/GetLibraryArtworkProviders.http new file mode 100644 index 00000000..5d6f41df --- /dev/null +++ b/docs/technical/requests/plugins/GetLibraryArtworkProviders.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/{{$guid}}/artwork-providers +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/plugins/ReorderLibraryArtworkProviders.http b/docs/technical/requests/plugins/ReorderLibraryArtworkProviders.http new file mode 100644 index 00000000..26b86886 --- /dev/null +++ b/docs/technical/requests/plugins/ReorderLibraryArtworkProviders.http @@ -0,0 +1,11 @@ +PUT {{host}}/api/v1/libraries/{{$guid}}/artwork-providers/reorder +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "libraryId": "{{$guid}}", + "pluginIds": [ + "{{$guid}}", + "{{$guid}}" + ] +} diff --git a/docs/technical/requests/plugins/SetLibraryArtworkProviderEnabled.http b/docs/technical/requests/plugins/SetLibraryArtworkProviderEnabled.http new file mode 100644 index 00000000..c12b851b --- /dev/null +++ b/docs/technical/requests/plugins/SetLibraryArtworkProviderEnabled.http @@ -0,0 +1,9 @@ +PUT {{host}}/api/v1/libraries/{{$guid}}/artwork-providers/{{$guid}}/enabled +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "libraryId": "{{$guid}}", + "pluginId": "{{$guid}}", + "isEnabled": true +} diff --git a/docs/technical/requests/themes/DeleteTheme.http b/docs/technical/requests/themes/management/DeleteTheme.http similarity index 100% rename from docs/technical/requests/themes/DeleteTheme.http rename to docs/technical/requests/themes/management/DeleteTheme.http diff --git a/docs/technical/requests/themes/InstallTheme.http b/docs/technical/requests/themes/management/InstallTheme.http similarity index 100% rename from docs/technical/requests/themes/InstallTheme.http rename to docs/technical/requests/themes/management/InstallTheme.http diff --git a/docs/technical/requests/themes/RestoreTheme.http b/docs/technical/requests/themes/management/RestoreTheme.http similarity index 100% rename from docs/technical/requests/themes/RestoreTheme.http rename to docs/technical/requests/themes/management/RestoreTheme.http diff --git a/docs/technical/requests/themes/SetCurrentTheme.http b/docs/technical/requests/themes/management/SetCurrentTheme.http similarity index 100% rename from docs/technical/requests/themes/SetCurrentTheme.http rename to docs/technical/requests/themes/management/SetCurrentTheme.http diff --git a/docs/technical/requests/themes/GetCurrentTheme.http b/docs/technical/requests/themes/queries/GetCurrentTheme.http similarity index 100% rename from docs/technical/requests/themes/GetCurrentTheme.http rename to docs/technical/requests/themes/queries/GetCurrentTheme.http diff --git a/docs/technical/requests/themes/GetThemeArchive.http b/docs/technical/requests/themes/queries/GetThemeArchive.http similarity index 100% rename from docs/technical/requests/themes/GetThemeArchive.http rename to docs/technical/requests/themes/queries/GetThemeArchive.http diff --git a/docs/technical/requests/themes/GetThemeAsset.http b/docs/technical/requests/themes/queries/GetThemeAsset.http similarity index 100% rename from docs/technical/requests/themes/GetThemeAsset.http rename to docs/technical/requests/themes/queries/GetThemeAsset.http diff --git a/docs/technical/requests/themes/GetThemeSettings.http b/docs/technical/requests/themes/queries/GetThemeSettings.http similarity index 100% rename from docs/technical/requests/themes/GetThemeSettings.http rename to docs/technical/requests/themes/queries/GetThemeSettings.http diff --git a/docs/technical/requests/themes/GetThemeTemplate.http b/docs/technical/requests/themes/queries/GetThemeTemplate.http similarity index 100% rename from docs/technical/requests/themes/GetThemeTemplate.http rename to docs/technical/requests/themes/queries/GetThemeTemplate.http diff --git a/docs/technical/requests/themes/GetThemes.http b/docs/technical/requests/themes/queries/GetThemes.http similarity index 100% rename from docs/technical/requests/themes/GetThemes.http rename to docs/technical/requests/themes/queries/GetThemes.http diff --git a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs index a6361e3b..fbfbbcd9 100644 --- a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs +++ b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; 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.MediaContributors; @@ -68,7 +67,7 @@ internal static class CalibreMapper /// The release information of the book, always present even when the publication date is missing. private static ReleaseInfoDto BuildReleaseInfo(DateTimeOffset? publishDate) { - // the release info must always be present, even when the publication date is missing, so that the metadata can be applied to the book + // The release info must always be present, even when the publication date is missing, so that the metadata can be applied to the book. if (publishDate is null) { return new ReleaseInfoDto( @@ -124,20 +123,20 @@ internal static class CalibreMapper List result = []; HashSet seen = new(StringComparer.OrdinalIgnoreCase); - void Add(string? displayName, string role, MediaContributorRoleCategory category) + void Add(string? displayName, MediaContributorRole role) { if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) return; result.Add(new MediaContributorDto( Name: new MediaContributorNameDto(DisplayName: displayName.Trim(), LegalName: null), - Role: new MediaContributorRoleDto(Name: role, Category: category)) + Role: role) ); } foreach (OpfCreatorDto creator in creators) - Add(creator.Name, "Author", MediaContributorRoleCategory.Author); + Add(creator.Name, MediaContributorRole.Author); foreach (OpfContributorDto contributor in contributors) - Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role)); + Add(contributor.Name, MapContributorRole(contributor.Role)); return result; } @@ -189,7 +188,7 @@ internal static class CalibreMapper private static string? NormalizeIsbn(string isbn) { string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant(); - // valid ISBNs must be 10 or 13 characters in length, all characters except the last one must be digits, and the last one must be a digit for ISBN-13 and X for ISBN-10 + // Valid ISBNs must be 10 or 13 characters in length, all characters except the last one must be digits, and the last one must be a digit for ISBN-13 and X for ISBN-10. if ((normalized.Length != 10 && normalized.Length != 13) || normalized[..^1].Any(character => !char.IsDigit(character)) || (!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X'))) @@ -214,30 +213,20 @@ internal static class CalibreMapper } /// - /// Maps a creator or contributor role code into a role name. + /// Maps a creator or contributor role code into the canonical role. /// /// The role code to map. - /// The mapped role name. - private static string MapContributorRole(string? role) - { - return string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) ? "Author" : string.IsNullOrWhiteSpace(role) ? "Contributor" : role; - } - - /// - /// Maps a creator or contributor role code into the canonical category of the role. - /// - /// The role code to map. - /// The canonical category of the role. - private static MediaContributorRoleCategory MapContributorCategory(string? role) + /// The canonical role. + private static MediaContributorRole MapContributorRole(string? role) { if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true) - return MediaContributorRoleCategory.Author; + return MediaContributorRole.Author; if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Illustrator; + return MediaContributorRole.Illustrator; if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Translator; + return MediaContributorRole.Translator; if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Publisher; - return MediaContributorRoleCategory.Other; + return MediaContributorRole.Publisher; + return MediaContributorRole.Other; } } diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs index bd94a8b0..ac093c3b 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs @@ -59,8 +59,8 @@ internal static partial class OpenLibraryMapper /// The authors of the book. /// The ratings of the book, or when no ratings were found. /// The search document used as a fallback source of data, or . - /// The mapped book request. - public static AddBookRequest MapDetailed( + /// The mapped book metadata. + public static BookMetadataDto MapDetailed( BookMetadataLookupDto lookup, OpenLibraryEditionResponse? edition, OpenLibraryWorkResponse? work, @@ -99,26 +99,23 @@ internal static partial class OpenLibraryMapper string? releaseCountry = edition?.PublishPlaces.FirstOrDefault() ?? fallback?.PublishPlaces.FirstOrDefault(); string? releaseVersion = edition?.EditionName; - return new AddBookRequest( - lookup.LibraryId, - lookup.Path, - new WrittenContentMetadataDto( - title, - work?.OriginalTitle, - description, - new ReleaseInfoDto( - originalRelease.Date, - originalYear, - editionRelease.Date, - editionRelease.Date?.Year ?? editionRelease.Year, - MapReleaseCountry(releaseCountry), - NullIfWhiteSpace(releaseVersion)), - [.. genreNames.Select(name => new GenreDto(name))], - [.. subjects.Select(name => new TagDto(name))], - MapLanguage(currentLanguageCode), - MapLanguage(originalLanguageCode), - edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(), - edition?.NumberOfPages ?? fallback?.NumberOfPagesMedian), + return new BookMetadataDto( + title, + work?.OriginalTitle, + description, + new ReleaseInfoDto( + originalRelease.Date, + originalYear, + editionRelease.Date, + editionRelease.Date?.Year ?? editionRelease.Year, + MapReleaseCountry(releaseCountry), + NullIfWhiteSpace(releaseVersion)), + [.. genreNames.Select(name => new GenreDto(name))], + [.. subjects.Select(name => new TagDto(name))], + MapLanguage(currentLanguageCode), + MapLanguage(originalLanguageCode), + edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(), + edition?.NumberOfPages ?? fallback?.NumberOfPagesMedian, MapFormat(edition?.PhysicalFormat), NullIfWhiteSpace(edition?.EditionName), ParseVolumeNumber(edition?.Volume, edition?.Series.FirstOrDefault()), @@ -134,7 +131,8 @@ internal static partial class OpenLibraryMapper NullIfWhiteSpace(appleBooksId), isbns, contributors, - mappedRatings); + mappedRatings, + CoverImagePath: null); } /// @@ -142,8 +140,8 @@ internal static partial class OpenLibraryMapper /// /// The lookup describing the book to map. /// The search document to map. - /// The mapped book request candidate. - public static AddBookRequest MapSearchCandidate(BookMetadataLookupDto lookup, OpenLibrarySearchDocumentResponse document) + /// The mapped book metadata candidate. + public static BookMetadataDto MapSearchCandidate(BookMetadataLookupDto lookup, OpenLibrarySearchDocumentResponse document) { return MapDetailed(lookup, null, null, [], null, document); } @@ -274,24 +272,24 @@ internal static partial class OpenLibraryMapper List result = []; HashSet seen = new(StringComparer.OrdinalIgnoreCase); - void Add(string? displayName, string? legalName, string role, MediaContributorRoleCategory category) + void Add(string? displayName, string? legalName, MediaContributorRole role) { if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) return; - result.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), NullIfWhiteSpace(legalName)), new MediaContributorRoleDto(role, category))); + result.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), NullIfWhiteSpace(legalName)), role)); } foreach (OpenLibraryAuthorResponse author in authors) - Add(author.Name, author.PersonalName, "Author", MediaContributorRoleCategory.Author); + Add(author.Name, author.PersonalName, MediaContributorRole.Author); foreach (string authorName in fallbackAuthors ?? []) - Add(authorName, null, "Author", MediaContributorRoleCategory.Author); + Add(authorName, null, MediaContributorRole.Author); foreach (string contribution in contributions ?? []) { Match match = ContributorPattern().Match(contribution); string name = match.Success ? match.Groups["name"].Value.Trim() : contribution.Trim(); - string role = match.Success ? match.Groups["role"].Value.Trim() : "Contributor"; - Add(name, null, role, ContributorCategory(role)); + string role = match.Success ? match.Groups["role"].Value.Trim() : string.Empty; + Add(name, null, ContributorRole(role)); } return result; } @@ -505,24 +503,24 @@ internal static partial class OpenLibraryMapper } /// - /// Maps a contribution role into the canonical category of the role. + /// Maps a contribution role into the canonical role. /// - /// The role to categorize. - /// The canonical category of the role. - private static MediaContributorRoleCategory ContributorCategory(string role) + /// The role to map. + /// The canonical role. + private static MediaContributorRole ContributorRole(string role) { if (role.Contains("illustr", StringComparison.OrdinalIgnoreCase) || role.Contains("artist", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Illustrator; + return MediaContributorRole.Illustrator; if (role.Contains("translat", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Translator; + return MediaContributorRole.Translator; if (role.Contains("narrat", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Narrator; + return MediaContributorRole.Narrator; if (role.Contains("edit", StringComparison.OrdinalIgnoreCase) || role.Contains("author", StringComparison.OrdinalIgnoreCase) || role.Contains("writer", StringComparison.OrdinalIgnoreCase)) - return MediaContributorRoleCategory.Author; - return MediaContributorRoleCategory.Other; + return MediaContributorRole.Author; + return MediaContributorRole.Other; } /// diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs index b247c5dd..98d728ed 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs @@ -65,75 +65,15 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); return [.. openLibrarySearchDocuments .Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title)) - .Select(openLibrarySearchDocument => - { - AddBookRequest addBookRequest = OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument); - return new BookMetadataDto( - addBookRequest.Metadata?.Title, - addBookRequest.Metadata?.OriginalTitle, - addBookRequest.Metadata?.Description, - addBookRequest.Metadata?.ReleaseInfo, - addBookRequest.Metadata?.Genres, - addBookRequest.Metadata?.Tags, - addBookRequest.Metadata?.Language, - addBookRequest.Metadata?.OriginalLanguage, - addBookRequest.Metadata?.Publisher, - addBookRequest.Metadata?.PageCount, - addBookRequest.Format, - addBookRequest.Edition, - addBookRequest.VolumeNumber, - addBookRequest.Series, - addBookRequest.ASIN, - addBookRequest.GoodreadsId, - addBookRequest.LCCN, - addBookRequest.OCLCNumber, - addBookRequest.OpenLibraryId, - addBookRequest.LibraryThingId, - addBookRequest.GoogleBooksId, - addBookRequest.BarnesAndNobleId, - addBookRequest.AppleBooksId, - addBookRequest.ISBNs, - addBookRequest.Contributors, - addBookRequest.Ratings, - CoverImagePath: null - ); - })]; + .Select(openLibrarySearchDocument => OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument))]; } /// @@ -144,45 +84,16 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProviderThe metadata of the media item, or when no metadata was found. public async Task GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) { - AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); - return exactBookRequestMatch is null ? null : new BookMetadataDto( - exactBookRequestMatch.Metadata?.Title, - exactBookRequestMatch.Metadata?.OriginalTitle, - exactBookRequestMatch.Metadata?.Description, - exactBookRequestMatch.Metadata?.ReleaseInfo, - exactBookRequestMatch.Metadata?.Genres, - exactBookRequestMatch.Metadata?.Tags, - exactBookRequestMatch.Metadata?.Language, - exactBookRequestMatch.Metadata?.OriginalLanguage, - exactBookRequestMatch.Metadata?.Publisher, - exactBookRequestMatch.Metadata?.PageCount, - exactBookRequestMatch.Format, - exactBookRequestMatch.Edition, - exactBookRequestMatch.VolumeNumber, - exactBookRequestMatch.Series, - exactBookRequestMatch.ASIN, - exactBookRequestMatch.GoodreadsId, - exactBookRequestMatch.LCCN, - exactBookRequestMatch.OCLCNumber, - exactBookRequestMatch.OpenLibraryId, - exactBookRequestMatch.LibraryThingId, - exactBookRequestMatch.GoogleBooksId, - exactBookRequestMatch.BarnesAndNobleId, - exactBookRequestMatch.AppleBooksId, - exactBookRequestMatch.ISBNs, - exactBookRequestMatch.Contributors, - exactBookRequestMatch.Ratings, - CoverImagePath: null - ); + return await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); } /// - /// Resolves the lookup into a full book request by combining edition, work, author, and rating data from Open Library. + /// Resolves the lookup into full book metadata by combining edition, work, author, and rating data from Open Library. /// /// The lookup describing the book to resolve. /// Cancellation token that can be used to stop the execution. - /// The resolved book request, or when no matching book was found. - public async Task GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default) + /// The resolved book metadata, or when no matching book was found. + public async Task GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default) { ValidateLookup(bookMetadataLookup); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs new file mode 100644 index 00000000..93b67e3a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Lightweight read model of an album, containing only the fields needed to display the album in a card-based grid or a list. +/// +public sealed record AlbumLiteRow +{ + /// + /// Gets the Id of the album. + /// + public required Guid Id { get; init; } + + /// + /// Gets the title of the album. + /// + public required string Title { get; init; } + + /// + /// Gets the number of tracks of the release. + /// + public int TotalTracks { get; init; } +} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs new file mode 100644 index 00000000..27aae3d4 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Lightweight read model of an artist, containing only the fields needed to display the artist in a card-based grid or a list. +/// +public sealed record ArtistLiteRow +{ + /// + /// Gets the Id of the artist. + /// + public required Guid Id { get; init; } + + /// + /// Gets the name of the artist. + /// + public required string Name { get; init; } +} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs new file mode 100644 index 00000000..2b21efcf --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Lightweight read model of a track, containing only the fields needed to display the track in a list. +/// +public sealed record TrackLiteRow +{ + /// + /// Gets the Id of the track. + /// + public required Guid Id { get; init; } + + /// + /// Gets the title of the track. + /// + public required string Title { get; init; } + + /// + /// Gets the number of the track on its disc. + /// + public int TrackNumber { get; init; } + + /// + /// Gets the number of the disc the track belongs to, if applicable. + /// + public int? DiscNumber { get; init; } +} diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs new file mode 100644 index 00000000..9a2e1b96 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list. +/// +public sealed record BookLiteRow +{ + /// + /// Gets the Id of the book. + /// + public required Guid Id { get; init; } + + /// + /// Gets the title of the book. + /// + public required string Title { get; init; } + + /// + /// Gets the release year of the book (re-release year, if available, or original release year), if known. + /// + public int? ReleaseYear { get; init; } + + /// + /// Gets the path of the image representing the cover of the book, if available. + /// + public string? CoverPath { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs index 019ecd4a..5c1befd0 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/GenreEntity.cs @@ -11,4 +11,4 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common; [DebuggerDisplay("Name: {Name}")] public record GenreEntity( string? Name -); +) : ISharedReferenceEntity; diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs new file mode 100644 index 00000000..99d3b4b3 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/ISharedReferenceEntity.cs @@ -0,0 +1,12 @@ +namespace Lumina.Application.Common.DataAccess.Entities.Common; + +/// +/// Interface for a shared reference entity, whose identity is its name and whose rows are shared across the whole storage medium instead of being owned by a single parent. +/// +public interface ISharedReferenceEntity +{ + /// + /// Gets the name that identifies the shared reference. + /// + string? Name { get; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs index f020608f..21536ad8 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/Common/TagEntity.cs @@ -11,4 +11,4 @@ namespace Lumina.Application.Common.DataAccess.Entities.Common; [DebuggerDisplay("Name: {Name}")] public record TagEntity( string? Name -); +) : ISharedReferenceEntity; diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntity.cs new file mode 100644 index 00000000..17a6b020 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntity.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for the participation of a media contributor in an album, carrying the role the contributor played in that album. +/// The role is tracked per participation, so that a single contributor can play multiple roles in the same album, or different roles in different albums. +/// +[DebuggerDisplay("AlbumId: {AlbumId} MediaContributorId: {MediaContributorId}")] +public class AlbumContributorEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the participation. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the album the contributor participated in. + /// + public required Guid AlbumId { get; init; } + + /// + /// Gets the Id of the media contributor. + /// + public required Guid MediaContributorId { get; init; } + + /// + /// Gets the role the contributor played in the album. + /// + public required MediaContributorRole Role { get; init; } + + /// + /// 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 Guid? UpdatedBy { get; set; } +} 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 new file mode 100644 index 00000000..2a5c2330 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for an album, a release of an artist. +/// +[DebuggerDisplay("Title: {Title}")] +public class AlbumEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the album. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the artist the album belongs to. + /// + public required Guid ArtistId { get; set; } + + /// + /// Gets or sets the Id of the media library the artist of the album belongs to. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the title of the album. + /// + public required string Title { get; set; } + + /// + /// Gets or sets the original title of the album, if applicable. + /// + public string? OriginalTitle { get; set; } + + /// + /// Gets or sets the description of the album, if applicable. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the original release date of the album, if applicable. + /// + public DateOnly? OriginalReleaseDate { get; set; } + + /// + /// Gets or sets the original release year of the album, if applicable. + /// + public int? OriginalReleaseYear { get; set; } + + /// + /// Gets or sets the re-release or reissue date of the album, if applicable. + /// + public DateOnly? ReReleaseDate { get; set; } + + /// + /// Gets or sets the re-release or reissue year of the album, if applicable. + /// + public int? ReReleaseYear { get; set; } + + /// + /// Gets or sets the country or region of release, if applicable. + /// + public ReleaseCountry? ReleaseCountry { get; set; } + + /// + /// Gets or sets the release version or edition of the album, if applicable. + /// + public string? ReleaseVersion { get; set; } + + /// + /// Gets or sets the ISO 639-1 two-letter language code of the album, if applicable. + /// + public string? LanguageCode { get; set; } + + /// + /// Gets or sets the full name of the language of the album in English, if applicable. + /// + public string? LanguageName { get; set; } + + /// + /// Gets or sets the native name of the language of the album, if applicable. + /// + public string? LanguageNativeName { get; set; } + + /// + /// Gets or sets the ISO 639-1 two-letter original language code of the album, if applicable. + /// + public string? OriginalLanguageCode { get; set; } + + /// + /// Gets or sets the full name of the original language of the album in English, if applicable. + /// + public string? OriginalLanguageName { get; set; } + + /// + /// Gets or sets the native name of the original language of the album, if applicable. + /// + public string? OriginalLanguageNativeName { get; set; } + + /// + /// Gets or sets the type of the release, if applicable. + /// + public MusicReleaseType? ReleaseType { get; set; } + + /// + /// Gets or sets the status of the release, if applicable. + /// + public MusicReleaseStatus? ReleaseStatus { get; set; } + + /// + /// Gets or sets the number of discs of the release, if applicable. + /// + public int? TotalDiscs { get; set; } + + /// + /// Gets or sets the number of tracks of the release. + /// + public int TotalTracks { get; set; } + + /// + /// Gets or sets the physical or digital medium of the album, if applicable. + /// + public MusicMediaFormat? MediaFormat { 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. + /// + public string? CatalogNumber { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the release, if applicable. + /// + public Guid? MusicBrainzReleaseId { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the release group, if applicable. + /// + public Guid? MusicBrainzReleaseGroupId { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the release artist, if applicable. + /// + public Guid? MusicBrainzReleaseArtistId { get; set; } + + /// + /// Gets or sets the artist the album belongs to. + /// + public ArtistEntity? Artist { get; set; } + + /// + /// Gets or sets the tracks of the album. + /// + public List Tracks { get; set; } = []; + + /// + /// Gets or sets the list of ratings for this album. + /// + public List Ratings { get; set; } = []; + + /// + /// Gets or sets the list of the media contributors of the album. + /// + public List Contributors { get; set; } = []; + + /// + /// Gets or sets the genres of the album. + /// + public HashSet Genres { get; set; } = []; + + /// + /// Gets or sets the tags of the album. + /// + public HashSet Tags { 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/ArtistContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistContributorEntity.cs new file mode 100644 index 00000000..c2d68a3f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistContributorEntity.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for the participation of a media contributor in an artist, carrying the role the contributor played in that artist. +/// The role is tracked per participation, so that a single contributor can play multiple roles in the same artist, or different roles in different artists. +/// +[DebuggerDisplay("ArtistId: {ArtistId} MediaContributorId: {MediaContributorId}")] +public class ArtistContributorEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the participation. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the artist the contributor participated in. + /// + public required Guid ArtistId { get; init; } + + /// + /// Gets the Id of the media contributor. + /// + public required Guid MediaContributorId { get; init; } + + /// + /// Gets the role the contributor played in the artist. + /// + public required MediaContributorRole Role { get; init; } + + /// + /// 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 Guid? UpdatedBy { get; set; } +} 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 new file mode 100644 index 00000000..5a01a28b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs @@ -0,0 +1,71 @@ +#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 an artist. +/// +[DebuggerDisplay("Name: {Name}")] +public class ArtistEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the artist. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the media library this artist belongs to. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the name of the artist. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the website of the artist, if applicable. + /// + public string? Website { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the artist, if applicable. + /// + public Guid? MusicBrainzArtistId { get; set; } + + /// + /// Gets or sets the albums of the artist. + /// + public List Albums { get; set; } = []; + + /// + /// Gets or sets the list of the media contributors that make up the artist. + /// + public List Contributors { 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/AudioRatingEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AudioRatingEntity.cs new file mode 100644 index 00000000..f0bfbbd7 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AudioRatingEntity.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for the rating of an audio media element. +/// +/// The rating value of the audio media element. +/// The maximum possible rating value of the audio media element. +/// The source of the audio rating (e.g., a specific website or platform). +/// The number of votes that contributed to the audio rating. +[DebuggerDisplay("{Value}/{MaxValue}")] +public record AudioRatingEntity( + decimal? Value, + decimal? MaxValue, + AudioRatingSource? Source, + int? VoteCount +) : RatingEntity(Value, MaxValue, VoteCount); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackContributorEntity.cs new file mode 100644 index 00000000..6681e401 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackContributorEntity.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for the participation of a media contributor in a track, carrying the role the contributor played in that track. +/// The role is tracked per participation, so that a single contributor can play multiple roles in the same track, or different roles in different tracks. +/// +[DebuggerDisplay("TrackId: {TrackId} MediaContributorId: {MediaContributorId}")] +public class TrackContributorEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the participation. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the track the contributor participated in. + /// + public required Guid TrackId { get; init; } + + /// + /// Gets the Id of the media contributor. + /// + public required Guid MediaContributorId { get; init; } + + /// + /// Gets the role the contributor played in the track. + /// + public required MediaContributorRole Role { get; init; } + + /// + /// 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 Guid? UpdatedBy { 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 new file mode 100644 index 00000000..8ea83524 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a track, the individual song of an album. +/// +[DebuggerDisplay("Title: {Title}")] +public class TrackEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the track. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the album the track belongs to. + /// + public required Guid AlbumId { get; set; } + + /// + /// Gets or sets the Id of the media library this track belongs to. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the file system path of the track. + /// + public required string Path { get; set; } + + /// + /// Gets or sets the title of the track. + /// + public required string Title { get; set; } + + /// + /// Gets or sets the original title of the track, if applicable. + /// + public string? OriginalTitle { get; set; } + + /// + /// Gets or sets the description of the track, if applicable. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the original release date of the track, if applicable. + /// + public DateOnly? OriginalReleaseDate { get; set; } + + /// + /// Gets or sets the original release year of the track, if applicable. + /// + public int? OriginalReleaseYear { get; set; } + + /// + /// Gets or sets the re-release or reissue date of the track, if applicable. + /// + public DateOnly? ReReleaseDate { get; set; } + + /// + /// Gets or sets the re-release or reissue year of the track, if applicable. + /// + public int? ReReleaseYear { get; set; } + + /// + /// Gets or sets the country or region of release, if applicable. + /// + public ReleaseCountry? ReleaseCountry { get; set; } + + /// + /// Gets or sets the release version or edition of the track, if applicable. + /// + public string? ReleaseVersion { get; set; } + + /// + /// Gets or sets the ISO 639-1 two-letter language code of the track, if applicable. + /// + public string? LanguageCode { get; set; } + + /// + /// Gets or sets the full name of the language of the track in English, if applicable. + /// + public string? LanguageName { get; set; } + + /// + /// Gets or sets the native name of the language of the track, if applicable. + /// + public string? LanguageNativeName { get; set; } + + /// + /// Gets or sets the ISO 639-1 two-letter original language code of the track, if applicable. + /// + public string? OriginalLanguageCode { get; set; } + + /// + /// Gets or sets the full name of the original language of the track in English, if applicable. + /// + public string? OriginalLanguageName { get; set; } + + /// + /// Gets or sets the native name of the original language of the track, if applicable. + /// + public string? OriginalLanguageNativeName { get; set; } + + /// + /// Gets or sets the duration of the audio in seconds. + /// + public int DurationInSeconds { get; set; } + + /// + /// Gets or sets the sample rate of the audio in Hz. + /// + public int SampleRate { get; set; } + + /// + /// Gets or sets the number of audio channels. + /// + public int Channels { get; set; } + + /// + /// Gets or sets the bit depth of the audio, if applicable. + /// + public int? BitDepth { get; set; } + + /// + /// Gets or sets 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 number of the track on its disc. + /// + public int TrackNumber { get; set; } + + /// + /// Gets or sets the number of the disc the track belongs to, if applicable. + /// + public int? DiscNumber { get; set; } + + /// + /// Gets or sets the script used by the language of the track, if applicable. + /// + public string? Script { get; set; } + + /// + /// Gets or sets the musical key of the track, if applicable. + /// + public MusicKey? Key { get; set; } + + /// + /// Gets or sets the tempo of the track in beats per minute, if applicable. + /// + public int? Bpm { get; set; } + + /// + /// Gets or sets the title of the work the track is a recording of, if applicable. + /// + public string? Work { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the recording, if applicable. + /// + public Guid? MusicBrainzRecordingId { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the track, if applicable. + /// + public Guid? MusicBrainzTrackId { get; set; } + + /// + /// Gets or sets the MusicBrainz identifier of the work, if applicable. + /// + public Guid? MusicBrainzWorkId { get; set; } + + /// + /// Gets or sets the album the track belongs to. + /// + public AlbumEntity? Album { get; set; } + + /// + /// Gets or sets the list of moods of the track. + /// + public List Moods { get; set; } = []; + + /// + /// Gets or sets the list of ISRC (International Standard Recording Code) of the track. + /// + public List Isrcs { get; set; } = []; + + /// + /// Gets or sets the list of the media contributors of the track. + /// + public List Contributors { get; set; } = []; + + /// + /// Gets or sets the list of ratings for this track. + /// + public List Ratings { get; set; } = []; + + /// + /// Gets or sets the genres of the track. + /// + public HashSet Genres { get; set; } = []; + + /// + /// Gets or sets the tags of the track. + /// + public HashSet Tags { 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/TrackIsrcEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackIsrcEntity.cs new file mode 100644 index 00000000..a6bf6978 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackIsrcEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for an ISRC (International Standard Recording Code) of a track. +/// +/// The value of the ISRC. +[DebuggerDisplay("Value: {Value}")] +public record TrackIsrcEntity( + string Value +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackMoodEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackMoodEntity.cs new file mode 100644 index 00000000..007a452f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackMoodEntity.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Repository entity for a mood of a track. +/// +/// The name of the mood. +[DebuggerDisplay("Name: {Name}")] +public record TrackMoodEntity( + string Name +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookContributorEntity.cs similarity index 60% rename from src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs rename to src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookContributorEntity.cs index 2aea5dde..daf32dc0 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaContributors/BookContributorEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookContributorEntity.cs @@ -5,12 +5,11 @@ using System; using System.Diagnostics; #endregion -namespace Lumina.Application.Common.DataAccess.Entities.MediaContributors; +namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; /// -/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor -/// played in that book. The role is tracked per participation, so that a single contributor can play multiple -/// roles in the same book, or different roles in different books. +/// Repository entity for the participation of a media contributor in a book, carrying the role the contributor played in that book. +/// The role is tracked per participation, so that a single contributor can play multiple roles in the same book, or different roles in different books. /// [DebuggerDisplay("BookId: {BookId} MediaContributorId: {MediaContributorId}")] public class BookContributorEntity : IStorageEntity, IAuditableEntity @@ -21,24 +20,19 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity public required Guid Id { get; init; } /// - /// Gets or sets the Id of the book the contributor participated in. + /// Gets the Id of the book the contributor participated in. /// - public required Guid BookId { get; set; } + public required Guid BookId { get; init; } /// - /// Gets or sets the Id of the media contributor. + /// Gets the Id of the media contributor. /// - public required Guid MediaContributorId { get; set; } + public required Guid MediaContributorId { get; init; } /// - /// Gets or sets the display name of the role the contributor played in the book. + /// Gets the role the contributor played in the book. /// - public required string RoleName { get; set; } - - /// - /// Gets or sets the canonical category of the role the contributor played in the book. - /// - public required MediaContributorRoleCategory RoleCategory { get; set; } + public required MediaContributorRole Role { get; init; } /// /// Gets or sets the time and date when the entity was added. @@ -58,5 +52,5 @@ public class BookContributorEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the optional Id of the user that updated the entity. /// - public required Guid? UpdatedBy { get; set; } + public Guid? UpdatedBy { 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 5bb5dabe..45779d8a 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 @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; @@ -185,7 +184,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the Barnes & Noble ID of the book. /// - public string? BarnesAndNobleId { get; set; } = null!; + public string? BarnesAndNobleId { get; set; } /// /// Gets or sets the Apple Books ID of the book. @@ -200,12 +199,12 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the participations of the media contributors in the book, each carrying the role the contributor played. /// - public List BookContributors { get; set; } = []; + public List Contributors { get; set; } = []; /// /// Gets or sets the pieces of artwork of the book, each tracked independently with its own enrichment state. /// - public List BookArtwork { get; set; } = []; + public List Artwork { get; set; } = []; /// /// Gets or sets the list of ratings for this book. diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs similarity index 93% rename from src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs rename to src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs index 3c59813c..64ddf7cd 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs @@ -3,13 +3,14 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; using Lumina.Application.Common.DataAccess.Repositories.Common.Base; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.Application.Common.DataAccess.Repositories.Books; +namespace Lumina.Application.Common.DataAccess.Repositories.BookLibrary; /// /// Interface for the repository for books. @@ -19,7 +20,8 @@ public interface IBookRepository : IRepository, IUpdateRepositoryAction, IGetByIdRepositoryAction, IGetAllRepositoryAction, - IGetPaginatedRepositoryAction + IGetAllLiteRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets all the books of the media library identified by . @@ -112,12 +114,4 @@ public interface IBookRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An containing either the display names of the authors of the books, keyed by book Id, or an error. Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken); - - /// - /// Deletes the book identified by . - /// - /// The Id of the book to delete. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - Task> DeleteAsync(Guid bookId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs new file mode 100644 index 00000000..929ee559 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IApplyUpdateRepositoryAction.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.Common.Primitives; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; + +/// +/// Interface defining the "apply update" action for interacting with a generic persistence medium. +/// +/// The type used for the apply update action. It should implement . +public interface IApplyUpdateRepositoryAction where TModel : IStorageEntity +{ + /// + /// Applies the editable values of onto the already tracked model, without loading it again. + /// + /// The tracked model whose editable values are updated. + /// The model carrying the desired values. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ApplyUpdateAsync(TModel tracked, TModel data, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs index 52efaa54..c5b7fdf9 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteAllRepositoryAction.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "delete all" action for interacting with a generic persistance medium. +/// Interface defining the "delete all" action for interacting with a generic persistence medium. /// public interface IDeleteAllRepositoryAction { diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs index 8a815923..dfb39383 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IDeleteByIdRepositoryAction.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "delete by id" action for interacting with a generic persistance medium. +/// Interface defining the "delete by id" action for interacting with a generic persistence medium. /// /// The type used for the identifier of the respository. It should not be . public interface IDeleteByIdRepositoryAction where TId : notnull diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs new file mode 100644 index 00000000..674de39b --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllLiteRepositoryAction.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; + +/// +/// Interface defining the "get all lite" action for interacting with a generic persistence medium. +/// It retrieves lightweight read models of the stored data, projecting only the fields needed to display +/// the data in grids or card-based navigation, without loading the full entities and their related data. +/// +/// The type stored in the persistence medium, which is projected into the lightweight read models. It should implement . +/// The type of the lightweight read models returned by the action. +public interface IGetAllLiteRepositoryAction where TModel : IStorageEntity +{ + /// + /// Gets the lightweight read models of type , projected from the data of type stored in the storage medium. + /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching data is returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a paginated result of type , or an error. + Task>> GetAllLiteAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto; +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs index 58f34768..5421e458 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetAllRepositoryAction.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Common; -using System.Collections.Generic; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using System.Threading; using System.Threading.Tasks; #endregion @@ -9,15 +11,22 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "get all" action for interacting with a generic persistance medium. +/// Interface defining the "get all" action for interacting with a generic persistence medium. /// /// The type used as a result for the "get all" action. It should implement . public interface IGetAllRepositoryAction where TModel : IStorageEntity { /// - /// Gets all data of type from the storage medium. + /// Gets data of type from the storage medium. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching data is returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - Task>> GetAllAsync(CancellationToken cancellationToken); + /// An containing either a paginated result of type , or an error. + Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto; } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs index 69d82b5b..2a749c52 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetByIdRepositoryAction.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "get by id" action for interacting with a generic persistance medium. +/// Interface defining the "get by id" action for interacting with a generic persistence medium. /// /// The type used as a result for the "get by id" action. It should implement . /// The type used for the identifier of the respository. It should not be . @@ -19,7 +19,9 @@ public interface IGetByIdRepositoryAction where TModel : IStorageEn /// Gets an element of type identified by from the storage medium. /// /// The id of the element to get. + /// Whether the navigation properties of the entity should be loaded together with the entity itself. Pass to retrieve only the data stored directly on the entity row. + /// Whether the retrieved entity should be tracked by the persistence medium, so that changes to it can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - Task> GetByIdAsync(TId id, CancellationToken cancellationToken); + Task> GetByIdAsync(TId id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetPaginatedRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetPaginatedRepositoryAction.cs deleted file mode 100644 index 21ca90ce..00000000 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IGetPaginatedRepositoryAction.cs +++ /dev/null @@ -1,30 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Common; -using Lumina.Application.Common.DTO.Filtering; -using Lumina.Application.Common.DTO.Pagination; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; - -/// -/// Interface defining the "get paginated" action for interacting with a generic persistence medium. -/// -/// The type used as a result for the "get paginated" action. It should implement . -public interface IGetPaginatedRepositoryAction where TModel : IStorageEntity -{ - /// - /// Gets paginated data of type from the storage medium. - /// - /// The type of the filter carrying the criteria used to filter the results. - /// The pagination data that includes current page and number of items per page to retrieve. If , all matching data is returned. - /// The name of the field by which to sort the results. - /// The direction in which to sort the results. - /// The model containing parameters used to filter results. - /// Cancellation token that can be used to stop the execution. - /// An containing either a paginated result of type , or an error. - Task>> GetPaginatedAsync(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto; -} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs index 4e817e5c..3faeb7c8 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "insert range" action for interacting with a generic persistance medium. +/// Interface defining the "insert range" action for interacting with a generic persistence medium. /// /// The type used for the insert range action. It should implement . public interface IInsertRangeRepositoryAction where TModel : IStorageEntity diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs index ce93bcfd..fdd91703 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRepositoryAction.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "insert" action for interacting with a generic persistance medium. +/// Interface defining the "insert" action for interacting with a generic persistence medium. /// /// The type used for the insert action. It should implement . public interface IInsertRepositoryAction where TModel : IStorageEntity diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs index a2ebb600..dd433a77 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IUpdateRepositoryAction.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions; /// -/// Interface defining the "update" action for interacting with a generic persistance medium. +/// Interface defining the "update" action for interacting with a generic persistence medium. /// /// The type used for the update action. It should implement . public interface IUpdateRepositoryAction where TModel : IStorageEntity diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs index 0e46fc4c..3a377255 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Base/IRepository.cs @@ -5,7 +5,7 @@ using Lumina.Application.Common.DataAccess.Entities.Common; namespace Lumina.Application.Common.DataAccess.Repositories.Common.Base; /// -/// Interface for interaction with a generic persistance medium. +/// Interface for interaction with a generic persistence medium. /// /// The type used for the repository. It should implement . public interface IRepository where TModel : IStorageEntity diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs new file mode 100644 index 00000000..f4103045 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs @@ -0,0 +1,41 @@ +#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.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +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 albums. +/// +public interface IAlbumRepository : IRepository, + IInsertRepositoryAction, + IUpdateRepositoryAction, + IApplyUpdateRepositoryAction, + IGetByIdRepositoryAction +{ + /// + /// Gets all the albums of the artist identified by . + /// + /// The Id of the artist whose albums are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByArtistIdAsync(Guid artistId, CancellationToken cancellationToken); + + /// + /// Gets the lightweight read models of the albums of the artist identified by , projecting only the fields needed to display the albums in a card-based grid or a list. + /// + /// The Id of the artist whose albums are retrieved. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching albums are returned. + /// 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); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs new file mode 100644 index 00000000..b15e7717 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs @@ -0,0 +1,22 @@ +#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.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; + +/// +/// Interface for the repository for artists. +/// +public interface IArtistRepository : IRepository, + IInsertRepositoryAction, + IUpdateRepositoryAction, + IGetByIdRepositoryAction, + IGetAllRepositoryAction, + IGetAllLiteRepositoryAction, + IDeleteByIdRepositoryAction +{ +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs new file mode 100644 index 00000000..b2720f5f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -0,0 +1,50 @@ +#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.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +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 tracks. +/// +public interface ITrackRepository : IRepository, + IInsertRepositoryAction, + IUpdateRepositoryAction, + IApplyUpdateRepositoryAction, + IGetByIdRepositoryAction +{ + /// + /// Gets the subset of that is already used by a track of the library identified by . + /// + /// The Id of the library whose tracks are searched. + /// The track 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 all the tracks of the album identified by . + /// + /// The Id of the album whose tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByAlbumIdAsync(Guid albumId, CancellationToken cancellationToken); + + /// + /// Gets the lightweight read models of the tracks of the album identified by , projecting only the fields needed to display the tracks of an album. + /// + /// The Id of the album whose tracks are retrieved. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching tracks are returned. + /// 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); +} diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 9c4c7407..f944b9f4 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -1,12 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Books; +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.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Domain.Common.Primitives; using System.Threading; using System.Threading.Tasks; #endregion @@ -43,6 +45,21 @@ public interface IUnitOfWork /// IBookRepository BookRepository { get; } + /// + /// Gets the artist repository. + /// + IArtistRepository ArtistRepository { get; } + + /// + /// Gets the album repository. + /// + IAlbumRepository AlbumRepository { get; } + + /// + /// Gets the track repository. + /// + ITrackRepository TrackRepository { get; } + /// /// Gets the media contributor repository. /// @@ -124,10 +141,11 @@ public interface IUnitOfWork IUserSettingsRepository UserSettingsRepository { get; } /// - /// Saves all changes made to the database. + /// Saves the changes made to the database. /// /// Cancellation token that can be used to stop the execution. - Task SaveChangesAsync(CancellationToken cancellationToken); + /// An representing either a successful operation, or an error. + Task> SaveChangesAsync(CancellationToken cancellationToken); /// /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. diff --git a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs index a216fd92..1edb0511 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Authorization.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Authorization.cs @@ -17,7 +17,8 @@ public static partial class Errors public static Error AdminRoleNotFound => Error.NotFound(description: nameof(AdminRoleNotFound)); public static Error AdminRoleCannotBeDeleted => Error.Forbidden(description: nameof(AdminRoleCannotBeDeleted)); public static Error RoleNotFound => Error.NotFound(description: nameof(RoleNotFound)); - public static Error PermissionAlreadyExists => Error.Unauthorized(description: nameof(PermissionAlreadyExists)); + public static Error PermissionNotFound => Error.NotFound(description: nameof(PermissionNotFound)); + public static Error PermissionAlreadyExists => Error.Conflict(description: nameof(PermissionAlreadyExists)); public static Error RoleAlreadyExists => Error.Conflict(description: nameof(RoleAlreadyExists)); public static Error RoleIdCannotBeEmpty => Error.Validation(description: nameof(RoleIdCannotBeEmpty)); public static Error PermissionsListCannotBeNull => Error.Validation(description: nameof(PermissionsListCannotBeNull)); diff --git a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs index 595dc8e0..df0b3197 100644 --- a/src/Lumina.Application/Common/Errors/Errors.Persistence.cs +++ b/src/Lumina.Application/Common/Errors/Errors.Persistence.cs @@ -13,5 +13,6 @@ public static partial class Errors { public static Error ErrorPersistingMediaLibrary => Error.Failure(description: nameof(ErrorPersistingMediaLibrary)); public static Error ErrorPersistingAuthorizationRole => Error.Failure(description: nameof(ErrorPersistingAuthorizationRole)); + public static Error UniqueConstraintViolation => Error.Conflict(description: nameof(UniqueConstraintViolation)); } } diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs index ca484383..86111ef8 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs @@ -32,7 +32,7 @@ internal sealed class ValidationRule : IValidationRule? _childValidator; @@ -56,7 +56,7 @@ internal sealed class ValidationRule : IValidationRule : IValidationRule : IValidationRule 0) + if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0) _instanceAwarePredicateErrors[^1] = validationError; - else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + else if (!isLastAddedPredicateInstanceAware && _predicateErrors.Count > 0) _predicateErrors[^1] = validationError; return this; } diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs index 75130e83..2ae08150 100644 --- a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs +++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs @@ -20,7 +20,7 @@ internal sealed class ValidationRuleForEach : IValidationRule _instanceAwarePredicateErrors = []; private Error currentError = Error.Validation(); private Func? condition; - private bool lastAddedPredicateIsInstanceAware; + private bool isLastAddedPredicateInstanceAware; private AbstractValidator? _childValidator; /// @@ -41,7 +41,7 @@ internal sealed class ValidationRuleForEach : IValidationRule : IValidationRule : IValidationRule 0) + if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0) _instanceAwarePredicateErrors[^1] = validationError; - else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + else if (!isLastAddedPredicateInstanceAware && _predicateErrors.Count > 0) _predicateErrors[^1] = validationError; return this; } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs index fc64e18b..6bcb848b 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreDtoMapping.cs @@ -23,7 +23,7 @@ public static class GenreDtoMapping public static Result ToDomainEntity(this GenreDto dto) { return Genre.Create( - dto.Name + dto.Name! ); } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs index 18106d78..535adbcd 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/GenreEntityMapping.cs @@ -46,7 +46,7 @@ public static class GenreEntityMapping public static Result ToDomainEntity(this GenreEntity repositoryEntity) { return Genre.Create( - repositoryEntity.Name ?? default + repositoryEntity.Name! ); } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs new file mode 100644 index 00000000..b466101a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/LanguageInfoDtoMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +#endregion + +namespace Lumina.Application.Common.Mapping.Common.Metadata; + +/// +/// Extension methods for converting . +/// +public static class LanguageInfoDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this LanguageInfoDto dto) + { + return LanguageInfo.Create( + dto.LanguageCode!, + dto.LanguageName!, + Optional.FromNullable(dto.NativeName) + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs new file mode 100644 index 00000000..366900cf --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/ReleaseInfoDtoMapping.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.Common.Metadata; + +/// +/// Extension methods for converting . +/// +public static class ReleaseInfoDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this ReleaseInfoDto dto) + { + return ReleaseInfo.Create( + Optional.FromNullable(dto.OriginalReleaseDate), + Optional.FromNullable(dto.OriginalReleaseYear), + Optional.FromNullable(dto.ReReleaseDate), + Optional.FromNullable(dto.ReReleaseYear), + Optional.FromNullable(dto.ReleaseCountry), + Optional.FromNullable(dto.ReleaseVersion) + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs index 9c987743..b86a6b7a 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagDtoMapping.cs @@ -23,7 +23,7 @@ public static class TagDtoMapping public static Result ToDomainEntity(this TagDto dto) { return Tag.Create( - dto.Name + dto.Name! ); } diff --git a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs index 45ef4409..04753f6e 100644 --- a/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Common/Metadata/TagEntityMapping.cs @@ -46,7 +46,7 @@ public static class TagEntityMapping public static Result ToDomainEntity(this TagEntity repositoryEntity) { return Tag.Create( - repositoryEntity.Name ?? default + repositoryEntity.Name! ); } diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs index b57de0a7..5a82ccf9 100644 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMapping.cs @@ -17,6 +17,6 @@ public static class GetDirectoriesRequestMapping /// The converted query. public static GetDirectoriesQuery ToQuery(this GetDirectoriesRequest request) { - return new GetDirectoriesQuery(request.Path, request.IncludeHiddenElements); + return new GetDirectoriesQuery(request.Path, request.ShouldIncludeHiddenElements); } } diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs index 76bda209..58ed16e4 100644 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMapping.cs @@ -17,6 +17,6 @@ public static class GetFilesRequestMapping /// The converted query. public static GetFilesQuery ToQuery(this GetFilesRequest request) { - return new GetFilesQuery(request.Path, request.IncludeHiddenElements); + return new GetFilesQuery(request.Path, request.ShouldIncludeHiddenElements); } } diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs index 0581cee4..05490543 100644 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMapping.cs @@ -17,6 +17,6 @@ public static class GetTreeFilesRequestMapping /// The converted query. public static GetTreeFilesQuery ToQuery(this GetTreeFilesRequest request) { - return new GetTreeFilesQuery(request.Path, request.IncludeHiddenElements); + return new GetTreeFilesQuery(request.Path, request.ShouldIncludeHiddenElements); } } diff --git a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMapping.cs index d34f0eb2..c67bd66a 100644 --- a/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/FileSystemManagement/Paths/CheckPathExistsRequestMapping.cs @@ -19,7 +19,7 @@ public static class CheckPathExistsRequestMapping { return new CheckPathExistsQuery( request.Path, - request.IncludeHiddenElements + request.ShouldIncludeHiddenElements ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaContributors/MediaContributorReferenceDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaContributors/MediaContributorReferenceDtoMapping.cs new file mode 100644 index 00000000..29a87226 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaContributors/MediaContributorReferenceDtoMapping.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +using AudioMediaContributorId = Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate.MediaContributorId; +using BookMediaContributorId = Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate.MediaContributorId; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaContributors; + +/// +/// Extension methods for converting . +/// +public static class MediaContributorReferenceDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToBookDomainEntity(this MediaContributorReferenceDto dto) + { + return BookMediaContributor.Create(BookMediaContributorId.Create(dto.ContributorId), dto.Role); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToBookDomainEntities(this IEnumerable dtos) + { + return dtos.Select(domainEntity => domainEntity.ToBookDomainEntity()); + } + + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToMusicDomainEntity(this MediaContributorReferenceDto dto) + { + return MusicMediaContributor.Create(AudioMediaContributorId.Create(dto.ContributorId), dto.Role); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToMusicDomainEntities(this IEnumerable dtos) + { + return dtos.Select(domainEntity => domainEntity.ToMusicDomainEntity()); + } +} 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 new file mode 100644 index 00000000..98c99dcc --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +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.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +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; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class AddAlbumCommandMapping +{ + /// + /// Converts to a domain . + /// + /// The command whose data is used to create the album. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result ToDomainEntity(this AddAlbumCommand command) + { + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + 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(); + errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainTracksResult = command.Tracks!.ToDomainEntities(); + errors = [.. domainTracksResult.Where(trackResult => trackResult.IsFailure).SelectMany(trackResult => trackResult.Errors)]; + if (errors.Count > 0) + return errors; + + Optional barcode = Optional.None(); + if (command.Barcode is not null) + { + Result barcodeResult = Barcode.Create(command.Barcode); + if (barcodeResult.IsFailure) + return barcodeResult.Errors; + barcode = barcodeResult.Value; + } + + Optional musicBrainzReleaseId = Optional.None(); + if (command.MusicBrainzReleaseId is not null) + musicBrainzReleaseId = MusicBrainzId.Create(command.MusicBrainzReleaseId.Value); + Optional musicBrainzReleaseGroupId = Optional.None(); + if (command.MusicBrainzReleaseGroupId is not null) + musicBrainzReleaseGroupId = MusicBrainzId.Create(command.MusicBrainzReleaseGroupId.Value); + Optional musicBrainzReleaseArtistId = Optional.None(); + if (command.MusicBrainzReleaseArtistId is not null) + musicBrainzReleaseArtistId = MusicBrainzId.Create(command.MusicBrainzReleaseArtistId.Value); + + List contributors = [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)]; + List ratings = [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]; + List tracks = [.. domainTracksResult.Select(trackResult => trackResult.Value)]; + + // An album carries an Id only when it already exists; otherwise a new one is minted. The repository preserves the stored + // creation audit when it merges an existing album, so a transient value is used here. + if (command.AlbumId.HasValue) + return Album.Create( + AlbumId.Create(command.AlbumId.Value), + metadataResult.Value, + Optional.FromNullable(command.MediaFormat), + barcode, + Optional.FromNullable(command.CatalogNumber), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + contributors, + ratings, + tracks, + DateTime.UtcNow, + Optional.None()); + + return Album.Create( + metadataResult.Value, + Optional.FromNullable(command.MediaFormat), + barcode, + Optional.FromNullable(command.CatalogNumber), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + contributors, + ratings, + tracks); + } + + /// + /// Converts to a collection of domain . + /// + /// The commands whose data is used to create the albums. + /// A collection of containing either the converted albums, or error messages. + public static IEnumerable> ToDomainEntities(this IEnumerable commands) + { + return commands.Select(command => command.ToDomainEntity()); + } +} 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 new file mode 100644 index 00000000..f769a908 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMapping.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class AddAlbumRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the album belongs to, taken from the route. + /// The Id of the artist the album belongs to, taken from the route. + /// The converted command. + public static AddAlbumCommand ToCommand(this AddAlbumRequest request, string? libraryId, string? artistId) + { + return new AddAlbumCommand( + libraryId, + artistId, + request.Metadata, + request.MediaFormat, + request.Barcode, + request.CatalogNumber, + request.MusicBrainzReleaseId, + request.MusicBrainzReleaseGroupId, + request.MusicBrainzReleaseArtistId, + request.Contributors, + request.Ratings, + request.Tracks?.ToCommands(libraryId, artistId, null).ToList()); + } + + /// + /// Converts to a collection of . + /// + /// The requests to be converted. + /// The Id of the library the albums belong to, taken from the route. + /// The Id of the artist the albums belong to, taken from the route. + /// The converted commands. + public static IEnumerable ToCommands(this IEnumerable requests, string? libraryId, string? artistId) + { + return requests.Select(request => request.ToCommand(libraryId, artistId)); + } +} 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 new file mode 100644 index 00000000..4335d734 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs @@ -0,0 +1,225 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +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.MediaContributorBoundedContext.MediaContributorAggregate; +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; +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; + +/// +/// Extension methods for converting . +/// +public static class AlbumEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AlbumEntity repositoryEntity) + { + Result releaseInfoResult = ReleaseInfo.Create( + Optional.FromNullable(repositoryEntity.OriginalReleaseDate), + Optional.FromNullable(repositoryEntity.OriginalReleaseYear), + Optional.FromNullable(repositoryEntity.ReReleaseDate), + Optional.FromNullable(repositoryEntity.ReReleaseYear), + Optional.FromNullable(repositoryEntity.ReleaseCountry), + Optional.FromNullable(repositoryEntity.ReleaseVersion)); + if (releaseInfoResult.IsFailure) + return releaseInfoResult.Errors; + + List domainGenres = []; + foreach (Result genreResult in repositoryEntity.Genres.ToDomainEntities()) + { + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (Result tagResult in repositoryEntity.Tags.ToDomainEntities()) + { + if (tagResult.IsFailure) + return tagResult.Errors; + domainTags.Add(tagResult.Value); + } + + Optional language = Optional.None(); + if (repositoryEntity.LanguageCode is not null && repositoryEntity.LanguageName is not null) + language = LanguageInfo.Create(repositoryEntity.LanguageCode, repositoryEntity.LanguageName, Optional.FromNullable(repositoryEntity.LanguageNativeName)); + + Optional originalLanguage = Optional.None(); + if (repositoryEntity.OriginalLanguageCode is not null && repositoryEntity.OriginalLanguageName is not null) + originalLanguage = LanguageInfo.Create(repositoryEntity.OriginalLanguageCode, repositoryEntity.OriginalLanguageName, Optional.FromNullable(repositoryEntity.OriginalLanguageNativeName)); + + Result metadataResult = AlbumMetadata.Create( + repositoryEntity.Title, + Optional.FromNullable(repositoryEntity.OriginalTitle), + Optional.FromNullable(repositoryEntity.Description), + releaseInfoResult.Value, + domainGenres, + domainTags, + language, + originalLanguage, + Optional.FromNullable(repositoryEntity.ReleaseType), + Optional.FromNullable(repositoryEntity.ReleaseStatus), + Optional.FromNullable(repositoryEntity.TotalDiscs), + repositoryEntity.TotalTracks); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + Optional barcode = Optional.None(); + if (repositoryEntity.Barcode is not null) + { + Result barcodeResult = Barcode.Create(repositoryEntity.Barcode); + if (barcodeResult.IsFailure) + return barcodeResult.Errors; + barcode = barcodeResult.Value; + } + + Optional musicBrainzReleaseId = Optional.None(); + if (repositoryEntity.MusicBrainzReleaseId is not null) + musicBrainzReleaseId = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseId.Value); + Optional musicBrainzReleaseGroupId = Optional.None(); + if (repositoryEntity.MusicBrainzReleaseGroupId is not null) + musicBrainzReleaseGroupId = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseGroupId.Value); + Optional musicBrainzReleaseArtistId = Optional.None(); + if (repositoryEntity.MusicBrainzReleaseArtistId is not null) + musicBrainzReleaseArtistId = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseArtistId.Value); + + List domainRatings = []; + foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainEntities()) + { + if (ratingResult.IsFailure) + return ratingResult.Errors; + domainRatings.Add(ratingResult.Value); + } + + List domainContributors = []; + foreach (AlbumContributorEntity contributorEntity in repositoryEntity.Contributors) + { + Result contributorResult = MusicMediaContributor.Create(MediaContributorId.Create(contributorEntity.MediaContributorId), contributorEntity.Role); + if (contributorResult.IsFailure) + return contributorResult.Errors; + domainContributors.Add(contributorResult.Value); + } + + List domainTracks = []; + foreach (TrackEntity trackEntity in repositoryEntity.Tracks) + { + Result trackResult = trackEntity.ToDomainEntity(); + if (trackResult.IsFailure) + return trackResult.Errors; + domainTracks.Add(trackResult.Value); + } + + return Album.Create( + AlbumId.Create(repositoryEntity.Id), + metadataResult.Value, + Optional.FromNullable(repositoryEntity.MediaFormat), + barcode, + Optional.FromNullable(repositoryEntity.CatalogNumber), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + domainContributors, + domainRatings, + domainTracks, + repositoryEntity.CreatedOnUtc, + Optional.FromNullable(repositoryEntity.UpdatedOnUtc)); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response entity. + public static AlbumResponse ToResponse(this AlbumEntity repositoryEntity) + { + ReleaseInfoDto releaseInfo = new( + repositoryEntity.OriginalReleaseDate, + repositoryEntity.OriginalReleaseYear, + repositoryEntity.ReReleaseDate, + repositoryEntity.ReReleaseYear, + repositoryEntity.ReleaseCountry, + repositoryEntity.ReleaseVersion + ); + // language and original language make sense only if their subproperties have values + LanguageInfoDto? languageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName) + ? new LanguageInfoDto( + repositoryEntity.LanguageCode, + repositoryEntity.LanguageName, + repositoryEntity.LanguageNativeName + ) : null; + LanguageInfoDto? originalLanguageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageNativeName) + ? new LanguageInfoDto( + repositoryEntity.OriginalLanguageCode, + repositoryEntity.OriginalLanguageName, + repositoryEntity.OriginalLanguageNativeName + ) : null; + AlbumMetadataDto metadata = new( + repositoryEntity.Title, + repositoryEntity.OriginalTitle, + repositoryEntity.Description, + releaseInfo, + languageInfo, + originalLanguageInfo, + [.. repositoryEntity.Tags.ToResponses()], + [.. repositoryEntity.Genres.ToResponses()], + repositoryEntity.ReleaseType, + repositoryEntity.ReleaseStatus, + repositoryEntity.TotalDiscs, + repositoryEntity.TotalTracks + ); + return new AlbumResponse( + repositoryEntity.Id, + repositoryEntity.ArtistId, + repositoryEntity.LibraryId, + metadata, + repositoryEntity.MediaFormat, + repositoryEntity.Barcode, + repositoryEntity.CatalogNumber, + repositoryEntity.MusicBrainzReleaseId, + repositoryEntity.MusicBrainzReleaseGroupId, + repositoryEntity.MusicBrainzReleaseArtistId, + repositoryEntity.CreatedOnUtc, + repositoryEntity.UpdatedOnUtc, + [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], + [.. repositoryEntity.Ratings.ToResponses()], + [.. repositoryEntity.Tracks.Select(track => track.ToResponse())]); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable repositoryEntities) + { + return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse())]; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMapping.cs new file mode 100644 index 00000000..4d5075a6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMapping.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class AlbumLiteRowMapping +{ + /// + /// Converts to . + /// + /// The read model to be converted. + /// The converted response. + public static AlbumLiteResponse ToResponse(this AlbumLiteRow readModel) + { + return new AlbumLiteResponse( + readModel.Id, + readModel.Title, + readModel.TotalTracks); + } + + /// + /// Converts to a collection of . + /// + /// The read models to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable readModels) + { + return [.. readModels.Select(readModel => readModel.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated read models to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto readModels) + { + return new PaginatedResponse + { + Data = readModels.Data.ToResponses(), + CurrentPage = readModels.CurrentPage, + PerPage = readModels.PerPage, + Count = readModels.Count, + NumberOfPages = readModels.NumberOfPages + }; + } +} 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 new file mode 100644 index 00000000..9a2cd2df --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using System; +using System.Linq; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +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; + +/// +/// Extension methods for converting . +/// +public static class AlbumMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The Id of the artist the album belongs to. + /// The Id of the media library the album belongs to. + /// The converted repository entity. + public static AlbumEntity ToRepositoryEntity(this Album domainEntity, Guid artistId, Guid libraryId) + { + return new AlbumEntity + { + Id = domainEntity.Id.Value, + ArtistId = artistId, + LibraryId = libraryId, + Title = domainEntity.Metadata.Title, + OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null, + Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.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, + ReReleaseYear = domainEntity.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseYear.Value : null, + ReleaseCountry = domainEntity.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseCountry.Value : null, + ReleaseVersion = domainEntity.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseVersion.Value : null, + LanguageCode = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageCode : null, + LanguageName = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageName : null, + LanguageNativeName = domainEntity.Metadata.Language.HasValue && domainEntity.Metadata.Language.Value.NativeName.HasValue ? domainEntity.Metadata.Language.Value.NativeName.Value : null, + 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, + Genres = [.. domainEntity.Metadata.Genres.ToRepositoryEntities()], + Tags = [.. domainEntity.Metadata.Tags.ToRepositoryEntities()], + ReleaseType = domainEntity.Metadata.ReleaseType.HasValue ? domainEntity.Metadata.ReleaseType.Value : null, + 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, + Barcode = domainEntity.Barcode.HasValue ? domainEntity.Barcode.Value.Value : null, + CatalogNumber = domainEntity.CatalogNumber.HasValue ? domainEntity.CatalogNumber.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, + Contributors = [.. domainEntity.Contributors.Select(contributor => new AlbumContributorEntity + { + Id = Guid.NewGuid(), + AlbumId = domainEntity.Id.Value, + MediaContributorId = contributor.ContributorId.Value, + Role = contributor.Role, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedBy = null + })], + Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], + Tracks = [.. domainEntity.Tracks.Select(track => track.ToRepositoryEntity(domainEntity.Id.Value, libraryId))], + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null + }; + } +} 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 new file mode 100644 index 00000000..84c3e609 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMapping.cs @@ -0,0 +1,81 @@ +#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 AlbumMetadataDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AlbumMetadataDto 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.ToDomainEntity(); + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (TagDto tag in dto.Tags ?? []) + { + Result tagResult = tag.ToDomainEntity(); + 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.Description), + releaseInfoResult.Value, + domainGenres, + domainTags, + language, + originalLanguage, + Optional.FromNullable(dto.ReleaseType), + Optional.FromNullable(dto.ReleaseStatus), + Optional.FromNullable(dto.TotalDiscs), + dto.TotalTracks ?? 0); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMapping.cs new file mode 100644 index 00000000..602efa84 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMapping.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class GetAlbumTracksLiteRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the album belongs to, taken from the route. + /// The Id of the artist the album belongs to, taken from the route. + /// The Id of the album whose tracks are retrieved, taken from the route. + /// The converted query. + public static GetAlbumTracksLiteQuery ToQuery(this GetAlbumTracksLiteRequest request, string? libraryId, string? artistId, string? albumId) + { + PaginationDataDto? paginationData = null; + if (request.CurrentPage is not null || request.PerPage is not null) + paginationData = new PaginationDataDto + { + CurrentPage = request.CurrentPage ?? 1, + PerPage = request.PerPage ?? 200 + }; + + return new GetAlbumTracksLiteQuery( + libraryId, + artistId, + albumId, + paginationData); + } +} 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 new file mode 100644 index 00000000..f7b8383e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +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.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.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class UpdateAlbumCommandMapping +{ + /// + /// Applies the editable data of to the album of identified by the command, through the aggregate root. + /// + /// The command whose data is applied to the album. + /// The artist aggregate that owns the album. + /// + /// An containing either the successfully updated , or an error message. + /// + public static Result ToDomainEntity(this UpdateAlbumCommand command, Artist artist) + { + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + 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(); + errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + Optional barcode = Optional.None(); + if (command.Barcode is not null) + { + Result barcodeResult = Barcode.Create(command.Barcode); + if (barcodeResult.IsFailure) + return barcodeResult.Errors; + barcode = barcodeResult.Value; + } + + Optional musicBrainzReleaseId = Optional.None(); + if (command.MusicBrainzReleaseId is not null) + musicBrainzReleaseId = MusicBrainzId.Create(command.MusicBrainzReleaseId.Value); + Optional musicBrainzReleaseGroupId = Optional.None(); + if (command.MusicBrainzReleaseGroupId is not null) + musicBrainzReleaseGroupId = MusicBrainzId.Create(command.MusicBrainzReleaseGroupId.Value); + Optional musicBrainzReleaseArtistId = Optional.None(); + if (command.MusicBrainzReleaseArtistId is not null) + musicBrainzReleaseArtistId = MusicBrainzId.Create(command.MusicBrainzReleaseArtistId.Value); + + // The album is an entity inside the artist aggregate, so it is referenced by object, not by id; the aggregate member is located here and passed through. + Album? album = artist.Albums.FirstOrDefault(album => album.Id.Value == Guid.Parse(command.AlbumId!)); + if (album is null) + return DomainErrors.Music.AlbumNotFound; + + Result updateResult = artist.UpdateAlbum( + album, + metadataResult.Value, + Optional.FromNullable(command.MediaFormat), + barcode, + Optional.FromNullable(command.CatalogNumber), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]); + if (updateResult.IsFailure) + return updateResult.Errors; + + return artist; + } +} 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 new file mode 100644 index 00000000..f75944de --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMapping.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Extension methods for converting . +/// +public static class UpdateAlbumRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the album belongs to, taken from the route. + /// The Id of the artist the album belongs to, taken from the route. + /// The Id of the album to update, taken from the route. + /// The converted command. + public static UpdateAlbumCommand ToCommand(this UpdateAlbumRequest request, string? libraryId, string? artistId, string? albumId) + { + return new UpdateAlbumCommand( + libraryId, + artistId, + albumId, + request.Metadata, + request.MediaFormat, + request.Barcode, + request.CatalogNumber, + request.MusicBrainzReleaseId, + request.MusicBrainzReleaseGroupId, + request.MusicBrainzReleaseArtistId, + request.Contributors, + request.Ratings); + } +} 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 new file mode 100644 index 00000000..9eb4c57f --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaContributors; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Domain.Common.Primitives; +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 System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class AddArtistCommandMapping +{ + /// + /// Converts to . + /// + /// The command to be converted. + /// The Id of the media library the artist is added to. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AddArtistCommand command, Guid libraryId) + { + // 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(); + List errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; + if (errors.Count > 0) + return errors; + + // Build each album of the artist, together with its metadata, contributors, ratings and tracks. + IEnumerable> domainAlbumsResult = command.Albums!.ToDomainEntities(); + errors = [.. domainAlbumsResult.Where(albumResult => albumResult.IsFailure).SelectMany(albumResult => albumResult.Errors)]; + if (errors.Count > 0) + return errors; + + Optional website = Optional.FromNullable(command.Website); + 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, + musicBrainzArtistId, + [.. 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 new file mode 100644 index 00000000..29691f5e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class AddArtistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the artist is added to, taken from the route. + /// The converted command. + public static AddArtistCommand ToCommand(this AddArtistRequest request, string? libraryId) + { + return new AddArtistCommand( + libraryId, + request.Name, + request.Website, + request.MusicBrainzArtistId, + request.Contributors, + 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 new file mode 100644 index 00000000..14e4335d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +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 System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class ArtistEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this ArtistEntity repositoryEntity) + { + Optional musicBrainzArtistId = Optional.None(); + if (repositoryEntity.MusicBrainzArtistId is not null) + musicBrainzArtistId = MusicBrainzId.Create(repositoryEntity.MusicBrainzArtistId.Value); + + List domainContributors = []; + foreach (ArtistContributorEntity contributorEntity in repositoryEntity.Contributors) + { + Result contributorResult = MusicMediaContributor.Create(MediaContributorId.Create(contributorEntity.MediaContributorId), contributorEntity.Role); + if (contributorResult.IsFailure) + return contributorResult.Errors; + domainContributors.Add(contributorResult.Value); + } + + List domainAlbums = []; + foreach (AlbumEntity albumEntity in repositoryEntity.Albums) + { + Result albumResult = albumEntity.ToDomainEntity(); + if (albumResult.IsFailure) + return albumResult.Errors; + domainAlbums.Add(albumResult.Value); + } + + return Artist.Create( + ArtistId.Create(repositoryEntity.Id), + LibraryId.Create(repositoryEntity.LibraryId), + repositoryEntity.Name, + Optional.FromNullable(repositoryEntity.Website), + musicBrainzArtistId, + domainContributors, + domainAlbums, + repositoryEntity.CreatedOnUtc, + Optional.FromNullable(repositoryEntity.UpdatedOnUtc)); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response entity. + public static ArtistResponse ToResponse(this ArtistEntity repositoryEntity) + { + return new ArtistResponse( + repositoryEntity.Id, + repositoryEntity.LibraryId, + repositoryEntity.Name, + repositoryEntity.Website, + repositoryEntity.MusicBrainzArtistId, + [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], + [.. repositoryEntity.Albums.Select(album => album.ToResponse())], + repositoryEntity.CreatedOnUtc, + repositoryEntity.UpdatedOnUtc); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable repositoryEntities) + { + return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated repository entities to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto repositoryEntities) + { + return new PaginatedResponse + { + Data = repositoryEntities.Data.ToResponses(), + CurrentPage = repositoryEntities.CurrentPage, + PerPage = repositoryEntities.PerPage, + Count = repositoryEntities.Count, + NumberOfPages = repositoryEntities.NumberOfPages + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMapping.cs new file mode 100644 index 00000000..b68bd3a7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMapping.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class ArtistLiteRowMapping +{ + /// + /// Converts to . + /// + /// The read model to be converted. + /// The converted response. + public static ArtistLiteResponse ToResponse(this ArtistLiteRow readModel) + { + return new ArtistLiteResponse( + readModel.Id, + readModel.Name); + } + + /// + /// Converts to a collection of . + /// + /// The read models to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable readModels) + { + return [.. readModels.Select(readModel => readModel.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated read models to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto readModels) + { + return new PaginatedResponse + { + Data = readModels.Data.ToResponses(), + CurrentPage = readModels.CurrentPage, + PerPage = readModels.PerPage, + Count = readModels.Count, + NumberOfPages = readModels.NumberOfPages + }; + } +} 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 new file mode 100644 index 00000000..7081307f --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using System; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class ArtistMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static ArtistEntity ToRepositoryEntity(this Artist domainEntity) + { + return new ArtistEntity + { + Id = domainEntity.Id.Value, + LibraryId = domainEntity.LibraryId.Value, + Name = domainEntity.Name, + Website = domainEntity.Website.HasValue ? domainEntity.Website.Value : null, + MusicBrainzArtistId = domainEntity.MusicBrainzArtistId.HasValue ? domainEntity.MusicBrainzArtistId.Value.Value : null, + Contributors = [.. domainEntity.Contributors.Select(contributor => new ArtistContributorEntity + { + Id = Guid.NewGuid(), + ArtistId = domainEntity.Id.Value, + MediaContributorId = contributor.ContributorId.Value, + Role = contributor.Role, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedBy = null + })], + Albums = [.. domainEntity.Albums.Select(album => album.ToRepositoryEntity(domainEntity.Id.Value, domainEntity.LibraryId.Value))], + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMapping.cs new file mode 100644 index 00000000..af21e1d1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class GetArtistAlbumsLiteRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the artist belongs to, taken from the route. + /// The Id of the artist whose albums are retrieved, taken from the route. + /// The converted query. + public static GetArtistAlbumsLiteQuery ToQuery(this GetArtistAlbumsLiteRequest request, string? libraryId, string? artistId) + { + PaginationDataDto? paginationData = null; + if (request.CurrentPage is not null || request.PerPage is not null) + paginationData = new PaginationDataDto + { + CurrentPage = request.CurrentPage ?? 1, + PerPage = request.PerPage ?? 200 + }; + + return new GetArtistAlbumsLiteQuery( + libraryId, + artistId, + paginationData); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMapping.cs new file mode 100644 index 00000000..2eebc351 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMapping.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class GetArtistsLiteRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library whose artists are retrieved, taken from the route. + /// The converted query. + public static GetArtistsLiteQuery ToQuery(this GetArtistsLiteRequest request, string? libraryId) + { + PaginationDataDto? paginationData = null; + if (request.CurrentPage is not null || request.PerPage is not null) + paginationData = new PaginationDataDto + { + CurrentPage = request.CurrentPage ?? 1, + PerPage = request.PerPage ?? 200 + }; + + return new GetArtistsLiteQuery( + libraryId, + paginationData, + request.SearchTerm); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMapping.cs new file mode 100644 index 00000000..c1809ab7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMapping.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class GetArtistsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library whose artists are retrieved, taken from the route. + /// The converted query. + public static GetArtistsQuery ToQuery(this GetArtistsRequest request, string? libraryId) + { + PaginationDataDto? paginationData = null; + if (request.CurrentPage is not null || request.PerPage is not null) + paginationData = new PaginationDataDto + { + CurrentPage = request.CurrentPage ?? 1, + PerPage = request.PerPage ?? 200 + }; + + return new GetArtistsQuery( + libraryId, + paginationData, + request.SearchTerm); + } +} 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 new file mode 100644 index 00000000..5231db18 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMapping.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class UpdateArtistAlbumRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the album belongs to, taken from the route. + /// The Id of the artist the album belongs to, taken from the route. + /// The converted command. + public static AddAlbumCommand ToCommand(this UpdateArtistAlbumRequest request, string? libraryId, string? artistId) + { + return new AddAlbumCommand( + libraryId, + artistId, + request.Metadata, + request.MediaFormat, + request.Barcode, + request.CatalogNumber, + request.MusicBrainzReleaseId, + request.MusicBrainzReleaseGroupId, + request.MusicBrainzReleaseArtistId, + request.Contributors, + request.Ratings, + request.Tracks?.ToCommands(libraryId, artistId, null).ToList(), + request.AlbumId); + } + + /// + /// Converts to a collection of . + /// + /// The requests to be converted. + /// The Id of the library the albums belong to, taken from the route. + /// The Id of the artist the albums belong to, taken from the route. + /// The converted commands. + public static IEnumerable ToCommands(this IEnumerable requests, string? libraryId, string? artistId) + { + return requests.Select(request => request.ToCommand(libraryId, artistId)); + } +} 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 new file mode 100644 index 00000000..90cbb234 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaContributors; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +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 System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class UpdateArtistCommandMapping +{ + /// + /// Applies the editable data of to , through the aggregate root. + /// + /// The command whose data is applied to the artist. + /// The artist aggregate to be updated. + /// + /// An containing either the successfully updated , or an error message. + /// + public static Result ToDomainEntity(this UpdateArtistCommand command, Artist artist) + { + // Map the media contributors that make up the artist to their domain counterparts. + IEnumerable> domainContributorsResult = command.Contributors!.ToMusicDomainEntities(); + List errors = [.. domainContributorsResult.Where(contributorResult => contributorResult.IsFailure).SelectMany(contributorResult => contributorResult.Errors)]; + if (errors.Count > 0) + return errors; + + // Build each album of the artist, together with its metadata, contributors, ratings and tracks. + IEnumerable> domainAlbumsResult = command.Albums!.ToDomainEntities(); + errors = [.. domainAlbumsResult.Where(albumResult => albumResult.IsFailure).SelectMany(albumResult => albumResult.Errors)]; + if (errors.Count > 0) + return errors; + + Optional website = Optional.FromNullable(command.Website); + 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); + if (updateDetailsResult.IsFailure) + return updateDetailsResult.Errors; + artist.UpdateContributors([.. domainContributorsResult.Select(contributorResult => contributorResult.Value)]); + + List domainAlbums = [.. domainAlbumsResult.Select(albumResult => albumResult.Value)]; + + // Reconcile the albums by their Id: existing albums and their tracks are updated in place, new albums are added, and albums that + // are no longer present are removed. New albums are added before the stale ones are removed, because an artist must always keep at least one album. + foreach (Album domainAlbum in domainAlbums) + { + // The existing album is the aggregate member, referenced by object, and is updated in place rather than being replaced. + Album? existingAlbum = artist.Albums.FirstOrDefault(album => album.Id == domainAlbum.Id); + if (existingAlbum is null) + { + Result addAlbumResult = artist.AddAlbum(domainAlbum); + if (addAlbumResult.IsFailure) + return addAlbumResult.Errors; + continue; + } + + Result updateAlbumResult = artist.UpdateAlbum( + existingAlbum, + domainAlbum.Metadata, + domainAlbum.MediaFormat, + domainAlbum.Barcode, + domainAlbum.CatalogNumber, + domainAlbum.MusicBrainzReleaseId, + domainAlbum.MusicBrainzReleaseGroupId, + domainAlbum.MusicBrainzReleaseArtistId, + domainAlbum.Contributors, + domainAlbum.Ratings); + if (updateAlbumResult.IsFailure) + return updateAlbumResult.Errors; + + // Reconcile the tracks by their Id: existing tracks are updated in place, new tracks are added, and tracks that are no longer present are removed. + foreach (Track domainTrack in domainAlbum.Tracks) + { + Track? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == domainTrack.Id); + if (existingTrack is null) + { + Result addTrackResult = artist.AddTrackToAlbum(existingAlbum, domainTrack); + if (addTrackResult.IsFailure) + return addTrackResult.Errors; + continue; + } + + Result updateTrackResult = artist.UpdateTrackInAlbum( + existingAlbum, + existingTrack, + domainTrack.Path, + domainTrack.Metadata, + domainTrack.TrackNumber, + domainTrack.DiscNumber, + domainTrack.Script, + domainTrack.Key, + domainTrack.Bpm, + domainTrack.Work, + domainTrack.MusicBrainzRecordingId, + domainTrack.MusicBrainzTrackId, + domainTrack.MusicBrainzWorkId, + domainTrack.Moods, + domainTrack.Isrcs, + domainTrack.Contributors, + domainTrack.Ratings); + if (updateTrackResult.IsFailure) + return updateTrackResult.Errors; + } + + foreach (Track staleTrack in existingAlbum.Tracks.Where(existingTrack => domainAlbum.Tracks.All(domainTrack => domainTrack.Id != existingTrack.Id)).ToList()) + { + Result removeTrackResult = artist.RemoveTrackFromAlbum(existingAlbum, staleTrack); + if (removeTrackResult.IsFailure) + return removeTrackResult.Errors; + } + } + + foreach (Album staleAlbum in artist.Albums.Where(existingAlbum => domainAlbums.All(domainAlbum => domainAlbum.Id != existingAlbum.Id)).ToList()) + { + Result removeAlbumResult = artist.RemoveAlbum(staleAlbum); + if (removeAlbumResult.IsFailure) + return removeAlbumResult.Errors; + } + + return artist; + } +} 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 new file mode 100644 index 00000000..2671a203 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class UpdateArtistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the artist belongs to, taken from the route. + /// The Id of the artist to update, taken from the route. + /// The converted command. + public static UpdateArtistCommand ToCommand(this UpdateArtistRequest request, string? libraryId, string? artistId) + { + return new UpdateArtistCommand( + libraryId, + artistId, + request.Name, + request.Website, + request.MusicBrainzArtistId, + request.Contributors, + 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 new file mode 100644 index 00000000..ea80bc90 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMapping.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Extension methods for converting . +/// +public static class UpdateArtistTrackRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the track belongs to, taken from the route. + /// The Id of the artist the track belongs to, taken from the route. + /// The Id of the album the track belongs to, taken from the route. + /// The converted command. + public static AddTrackCommand ToCommand(this UpdateArtistTrackRequest request, string? libraryId, string? artistId, string? albumId) + { + return new AddTrackCommand( + libraryId, + artistId, + albumId, + request.Path, + request.Metadata, + request.TrackNumber, + request.DiscNumber, + request.Script, + request.Key, + request.Bpm, + request.Work, + request.MusicBrainzRecordingId, + request.MusicBrainzTrackId, + request.MusicBrainzWorkId, + request.Moods, + request.Isrcs, + request.Contributors, + request.Ratings, + request.TrackId); + } + + /// + /// Converts to a collection of . + /// + /// The requests to be converted. + /// The Id of the library the tracks belong to, taken from the route. + /// The Id of the artist the tracks belong to, taken from the route. + /// The Id of the album the tracks belong to, taken from the route. + /// The converted commands. + public static IEnumerable ToCommands(this IEnumerable requests, string? libraryId, string? artistId, string? albumId) + { + return requests.Select(request => request.ToCommand(libraryId, artistId, albumId)); + } +} 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 new file mode 100644 index 00000000..c16bad24 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMapping.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class AudioRatingDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AudioRatingDto dto) + { + return AudioRating.Create( + dto.Value ?? default, + dto.MaxValue ?? default, + Optional.FromNullable(dto.Source), + Optional.FromNullable(dto.VoteCount) + ); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(dto => dto.ToDomainEntity()); + } +} 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 new file mode 100644 index 00000000..07dfa39c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMapping.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class AudioRatingEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static AudioRatingDto ToResponse(this AudioRatingEntity repositoryEntity) + { + return new AudioRatingDto( + repositoryEntity.Value ?? default, + repositoryEntity.MaxValue ?? default, + repositoryEntity.Source, + repositoryEntity.VoteCount + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AudioRatingEntity repositoryEntity) + { + return AudioRating.Create( + repositoryEntity.Value ?? default, + repositoryEntity.MaxValue ?? default, + Optional.FromNullable(repositoryEntity.Source), + Optional.FromNullable(repositoryEntity.VoteCount) + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMapping.cs new file mode 100644 index 00000000..713a7a17 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.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 AudioRatingMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static AudioRatingEntity ToRepositoryEntity(this AudioRating domainEntity) + { + return new AudioRatingEntity( + domainEntity.Value, + domainEntity.MaxValue, + domainEntity.Source.HasValue ? domainEntity.Source.Value : null, + domainEntity.VoteCount.HasValue ? domainEntity.VoteCount.Value : null + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity()); + } +} 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 new file mode 100644 index 00000000..ee7951b6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.Primitives; +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 IsrcDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this IsrcDto dto) + { + return Isrc.Create(dto.Value!); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(dto => dto.ToDomainEntity()); + } +} 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 new file mode 100644 index 00000000..4499e159 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMapping.cs @@ -0,0 +1,62 @@ +#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.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 IsrcEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static IsrcDto ToResponse(this TrackIsrcEntity repositoryEntity) + { + return new IsrcDto( + repositoryEntity.Value + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this TrackIsrcEntity repositoryEntity) + { + return Isrc.Create(repositoryEntity.Value!); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMapping.cs new file mode 100644 index 00000000..88fe7b91 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMapping.cs @@ -0,0 +1,36 @@ +#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 IsrcMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static TrackIsrcEntity ToRepositoryEntity(this Isrc domainEntity) + { + return new TrackIsrcEntity( + domainEntity.Value + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static IEnumerable ToRepositoryEntities(this IEnumerable domainEntities) + { + return domainEntities.Select(domainEntity => domainEntity.ToRepositoryEntity()); + } +} 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 new file mode 100644 index 00000000..661ec0ed --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMapping.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MoodDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this MoodDto dto) + { + return Mood.Create(dto.Name!); + } + + /// + /// Converts to a collection of . + /// + /// The DTOs to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable dtos) + { + return dtos.Select(dto => dto.ToDomainEntity()); + } +} 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 new file mode 100644 index 00000000..b70c86d3 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMapping.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MoodEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted DTO. + public static MoodDto ToResponse(this TrackMoodEntity repositoryEntity) + { + return new MoodDto( + repositoryEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted DTOs. + public static IEnumerable ToResponses(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse()); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this TrackMoodEntity repositoryEntity) + { + return Mood.Create(repositoryEntity.Name!); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// + /// An containing either a collection of converted , or an error message. + /// + public static IEnumerable> ToDomainEntities(this IEnumerable repositoryEntities) + { + return repositoryEntities.Select(repositoryEntity => repositoryEntity.ToDomainEntity()); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMapping.cs new file mode 100644 index 00000000..fe28c9fd --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMapping.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class MoodMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static TrackMoodEntity ToRepositoryEntity(this Mood domainEntity) + { + return new TrackMoodEntity( + domainEntity.Name + ); + } + + /// + /// Converts to a collection of . + /// + /// The domain entities to be converted. + /// The converted repository entities. + public static IEnumerable 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 new file mode 100644 index 00000000..e609bdf1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +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.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +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; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class AddTrackCommandMapping +{ + /// + /// Converts to a domain . + /// + /// The command whose data is used to create the track. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result ToDomainEntity(this AddTrackCommand command) + { + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainEntities(); + List errors = [.. domainMoodsResult.Where(moodResult => moodResult.IsFailure).SelectMany(moodResult => moodResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainIsrcsResult = (command.Isrcs ?? []).ToDomainEntities(); + errors = [.. domainIsrcsResult.Where(isrcResult => isrcResult.IsFailure).SelectMany(isrcResult => isrcResult.Errors)]; + if (errors.Count > 0) + return errors; + + 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(); + errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + 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)]; + List contributors = [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)]; + List ratings = [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]; + + // A track carries an Id only when it already exists; otherwise a new one is minted. + if (command.TrackId.HasValue) + return Track.Create( + TrackId.Create(command.TrackId.Value), + command.Path!, + metadataResult.Value, + command.TrackNumber!.Value, + Optional.FromNullable(command.DiscNumber), + moods, + Optional.FromNullable(command.Script), + Optional.FromNullable(command.Key), + Optional.FromNullable(command.Bpm), + isrcs, + Optional.FromNullable(command.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + contributors, + ratings, + DateTime.UtcNow, + Optional.None()); + + return Track.Create( + command.Path!, + metadataResult.Value, + command.TrackNumber!.Value, + Optional.FromNullable(command.DiscNumber), + moods, + Optional.FromNullable(command.Script), + Optional.FromNullable(command.Key), + Optional.FromNullable(command.Bpm), + isrcs, + Optional.FromNullable(command.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + contributors, + ratings); + } + + /// + /// Converts to a collection of domain . + /// + /// The commands whose data is used to create the tracks. + /// A collection of containing either the converted tracks, or error messages. + public static IEnumerable> ToDomainEntities(this IEnumerable commands) + { + return commands.Select(command => command.ToDomainEntity()); + } +} 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 new file mode 100644 index 00000000..9ada3803 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMapping.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class AddTrackRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the track belongs to, taken from the route. + /// The Id of the artist the track belongs to, taken from the route. + /// The Id of the album the track belongs to, taken from the route. + /// The converted command. + public static AddTrackCommand ToCommand(this AddTrackRequest request, string? libraryId, string? artistId, string? albumId) + { + return new AddTrackCommand( + libraryId, + artistId, + albumId, + request.Path, + request.Metadata, + request.TrackNumber, + request.DiscNumber, + request.Script, + request.Key, + request.Bpm, + request.Work, + request.MusicBrainzRecordingId, + request.MusicBrainzTrackId, + request.MusicBrainzWorkId, + request.Moods, + request.Isrcs, + request.Contributors, + request.Ratings); + } + + /// + /// Converts to a collection of . + /// + /// The requests to be converted. + /// The Id of the library the tracks belong to, taken from the route. + /// The Id of the artist the tracks belong to, taken from the route. + /// The Id of the album the tracks belong to, taken from the route. + /// The converted commands. + public static IEnumerable ToCommands(this IEnumerable requests, string? libraryId, string? artistId, string? albumId) + { + return requests.Select(request => request.ToCommand(libraryId, artistId, albumId)); + } +} 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 new file mode 100644 index 00000000..0642529c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.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.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 AudioMetadataDtoMapping +{ + /// + /// Converts to a domain . + /// + /// The data transfer object to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AudioMetadataDto 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.ToDomainEntity(); + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (TagDto tag in dto.Tags ?? []) + { + Result tagResult = tag.ToDomainEntity(); + 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)); + } +} 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 new file mode 100644 index 00000000..3689e5c8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs @@ -0,0 +1,236 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +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; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class TrackEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this TrackEntity repositoryEntity) + { + Result releaseInfoResult = ReleaseInfo.Create( + Optional.FromNullable(repositoryEntity.OriginalReleaseDate), + Optional.FromNullable(repositoryEntity.OriginalReleaseYear), + Optional.FromNullable(repositoryEntity.ReReleaseDate), + Optional.FromNullable(repositoryEntity.ReReleaseYear), + Optional.FromNullable(repositoryEntity.ReleaseCountry), + Optional.FromNullable(repositoryEntity.ReleaseVersion)); + if (releaseInfoResult.IsFailure) + return releaseInfoResult.Errors; + + List domainGenres = []; + foreach (Result genreResult in repositoryEntity.Genres.ToDomainEntities()) + { + if (genreResult.IsFailure) + return genreResult.Errors; + domainGenres.Add(genreResult.Value); + } + + List domainTags = []; + foreach (Result tagResult in repositoryEntity.Tags.ToDomainEntities()) + { + if (tagResult.IsFailure) + return tagResult.Errors; + domainTags.Add(tagResult.Value); + } + + Optional language = Optional.None(); + if (repositoryEntity.LanguageCode is not null && repositoryEntity.LanguageName is not null) + language = LanguageInfo.Create(repositoryEntity.LanguageCode, repositoryEntity.LanguageName, Optional.FromNullable(repositoryEntity.LanguageNativeName)); + + Optional originalLanguage = Optional.None(); + if (repositoryEntity.OriginalLanguageCode is not null && repositoryEntity.OriginalLanguageName is not null) + originalLanguage = LanguageInfo.Create(repositoryEntity.OriginalLanguageCode, repositoryEntity.OriginalLanguageName, Optional.FromNullable(repositoryEntity.OriginalLanguageNativeName)); + + Result metadataResult = AudioMetadata.Create( + repositoryEntity.Title, + Optional.FromNullable(repositoryEntity.OriginalTitle), + repositoryEntity.DurationInSeconds, + repositoryEntity.SampleRate, + repositoryEntity.Channels, + releaseInfoResult.Value, + Optional.FromNullable(repositoryEntity.Description), + domainGenres, + domainTags, + language, + originalLanguage, + Optional.FromNullable(repositoryEntity.BitDepth), + Optional.FromNullable(repositoryEntity.AudioCodec), + Optional.FromNullable(repositoryEntity.Bitrate)); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + Optional musicBrainzRecordingId = Optional.None(); + if (repositoryEntity.MusicBrainzRecordingId is not null) + musicBrainzRecordingId = MusicBrainzId.Create(repositoryEntity.MusicBrainzRecordingId.Value); + 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); + + List domainMoods = []; + foreach (Result moodResult in repositoryEntity.Moods.ToDomainEntities()) + { + if (moodResult.IsFailure) + return moodResult.Errors; + domainMoods.Add(moodResult.Value); + } + + List domainIsrcs = []; + foreach (Result isrcResult in repositoryEntity.Isrcs.ToDomainEntities()) + { + if (isrcResult.IsFailure) + return isrcResult.Errors; + domainIsrcs.Add(isrcResult.Value); + } + + List domainRatings = []; + foreach (Result ratingResult in repositoryEntity.Ratings.ToDomainEntities()) + { + if (ratingResult.IsFailure) + return ratingResult.Errors; + domainRatings.Add(ratingResult.Value); + } + + List domainContributors = []; + foreach (TrackContributorEntity contributorEntity in repositoryEntity.Contributors) + { + Result contributorResult = MusicMediaContributor.Create(MediaContributorId.Create(contributorEntity.MediaContributorId), contributorEntity.Role); + if (contributorResult.IsFailure) + return contributorResult.Errors; + domainContributors.Add(contributorResult.Value); + } + + return Track.Create( + TrackId.Create(repositoryEntity.Id), + repositoryEntity.Path, + metadataResult.Value, + repositoryEntity.TrackNumber, + Optional.FromNullable(repositoryEntity.DiscNumber), + domainMoods, + Optional.FromNullable(repositoryEntity.Script), + Optional.FromNullable(repositoryEntity.Key), + Optional.FromNullable(repositoryEntity.Bpm), + domainIsrcs, + Optional.FromNullable(repositoryEntity.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + domainContributors, + domainRatings, + repositoryEntity.CreatedOnUtc, + Optional.FromNullable(repositoryEntity.UpdatedOnUtc)); + } + + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The converted response entity. + public static TrackResponse ToResponse(this TrackEntity repositoryEntity) + { + ReleaseInfoDto releaseInfo = new( + repositoryEntity.OriginalReleaseDate, + repositoryEntity.OriginalReleaseYear, + repositoryEntity.ReReleaseDate, + repositoryEntity.ReReleaseYear, + repositoryEntity.ReleaseCountry, + repositoryEntity.ReleaseVersion + ); + // language and original language make sense only if their subproperties have values + LanguageInfoDto? languageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName) + ? new LanguageInfoDto( + repositoryEntity.LanguageCode, + repositoryEntity.LanguageName, + repositoryEntity.LanguageNativeName + ) : null; + LanguageInfoDto? originalLanguageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageCode) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageName) || + !string.IsNullOrWhiteSpace(repositoryEntity.OriginalLanguageNativeName) + ? new LanguageInfoDto( + repositoryEntity.OriginalLanguageCode, + repositoryEntity.OriginalLanguageName, + repositoryEntity.OriginalLanguageNativeName + ) : null; + AudioMetadataDto metadata = new( + repositoryEntity.Title, + repositoryEntity.OriginalTitle, + repositoryEntity.Description, + releaseInfo, + languageInfo, + originalLanguageInfo, + [.. repositoryEntity.Tags.ToResponses()], + [.. repositoryEntity.Genres.ToResponses()], + repositoryEntity.DurationInSeconds, + repositoryEntity.SampleRate, + repositoryEntity.Channels, + repositoryEntity.BitDepth, + repositoryEntity.AudioCodec, + repositoryEntity.Bitrate + ); + return new TrackResponse( + repositoryEntity.Id, + repositoryEntity.AlbumId, + repositoryEntity.LibraryId, + repositoryEntity.Path, + metadata, + repositoryEntity.TrackNumber, + repositoryEntity.DiscNumber, + repositoryEntity.Script, + repositoryEntity.Key, + repositoryEntity.Bpm, + repositoryEntity.Work, + repositoryEntity.MusicBrainzRecordingId, + repositoryEntity.MusicBrainzTrackId, + repositoryEntity.MusicBrainzWorkId, + repositoryEntity.CreatedOnUtc, + repositoryEntity.UpdatedOnUtc, + [.. repositoryEntity.Moods.ToResponses()], + [.. repositoryEntity.Isrcs.ToResponses()], + [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], + [.. repositoryEntity.Ratings.ToResponses()]); + } + + /// + /// Converts to a collection of . + /// + /// The repository entities to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable repositoryEntities) + { + return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToResponse())]; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMapping.cs new file mode 100644 index 00000000..a32662b9 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMapping.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class TrackLiteRowMapping +{ + /// + /// Converts to . + /// + /// The read model to be converted. + /// The converted response. + public static TrackLiteResponse ToResponse(this TrackLiteRow readModel) + { + return new TrackLiteResponse( + readModel.Id, + readModel.Title, + readModel.TrackNumber, + readModel.DiscNumber); + } + + /// + /// Converts to a collection of . + /// + /// The read models to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable readModels) + { + return [.. readModels.Select(readModel => readModel.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated read models to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto readModels) + { + return new PaginatedResponse + { + Data = readModels.Data.ToResponses(), + CurrentPage = readModels.CurrentPage, + PerPage = readModels.PerPage, + Count = readModels.Count, + NumberOfPages = readModels.NumberOfPages + }; + } +} 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 new file mode 100644 index 00000000..087d386a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using System; +using System.Linq; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class TrackMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The Id of the album the track belongs to. + /// The Id of the media library the album of the track belongs to. + /// The converted repository entity. + public static TrackEntity ToRepositoryEntity(this Track domainEntity, Guid albumId, Guid libraryId) + { + return new TrackEntity + { + Id = domainEntity.Id.Value, + AlbumId = albumId, + LibraryId = libraryId, + Path = domainEntity.Path, + Title = domainEntity.Metadata.Title, + OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null, + Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.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, + ReReleaseYear = domainEntity.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? domainEntity.Metadata.ReleaseInfo.ReReleaseYear.Value : null, + ReleaseCountry = domainEntity.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseCountry.Value : null, + ReleaseVersion = domainEntity.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? domainEntity.Metadata.ReleaseInfo.ReleaseVersion.Value : null, + LanguageCode = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageCode : null, + LanguageName = domainEntity.Metadata.Language.HasValue ? domainEntity.Metadata.Language.Value.LanguageName : null, + LanguageNativeName = domainEntity.Metadata.Language.HasValue && domainEntity.Metadata.Language.Value.NativeName.HasValue ? domainEntity.Metadata.Language.Value.NativeName.Value : null, + 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, + Genres = [.. domainEntity.Metadata.Genres.ToRepositoryEntities()], + Tags = [.. domainEntity.Metadata.Tags.ToRepositoryEntities()], + DurationInSeconds = domainEntity.Metadata.DurationInSeconds, + SampleRate = domainEntity.Metadata.SampleRate, + Channels = domainEntity.Metadata.Channels, + 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, + 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, + 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, + Contributors = [.. domainEntity.Contributors.Select(contributor => new TrackContributorEntity + { + Id = Guid.NewGuid(), + TrackId = domainEntity.Id.Value, + MediaContributorId = contributor.ContributorId.Value, + Role = contributor.Role, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedBy = null + })], + Moods = [.. domainEntity.Moods.ToRepositoryEntities()], + Isrcs = [.. domainEntity.Isrcs.ToRepositoryEntities()], + Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null + }; + } +} 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 new file mode 100644 index 00000000..ee4d7bda --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +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.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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class UpdateTrackCommandMapping +{ + /// + /// Applies the editable data of to the track of identified by the command, through the aggregate root. + /// + /// The command whose data is applied to the track. + /// The artist aggregate that owns the track. + /// + /// An containing either the successfully updated , or an error message. + /// + public static Result ToDomainEntity(this UpdateTrackCommand command, Artist artist) + { + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainEntities(); + List errors = [.. domainMoodsResult.Where(moodResult => moodResult.IsFailure).SelectMany(moodResult => moodResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainIsrcsResult = (command.Isrcs ?? []).ToDomainEntities(); + errors = [.. domainIsrcsResult.Where(isrcResult => isrcResult.IsFailure).SelectMany(isrcResult => isrcResult.Errors)]; + if (errors.Count > 0) + return errors; + + 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(); + errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + 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!)); + if (album is null) + return DomainErrors.Music.AlbumNotFound; + Track? track = album.Tracks.FirstOrDefault(track => track.Id.Value == Guid.Parse(command.TrackId!)); + if (track is null) + return DomainErrors.Music.TrackNotFound; + + Result updateResult = artist.UpdateTrackInAlbum( + album, + track, + command.Path!, + metadataResult.Value, + command.TrackNumber!.Value, + Optional.FromNullable(command.DiscNumber), + Optional.FromNullable(command.Script), + Optional.FromNullable(command.Key), + Optional.FromNullable(command.Bpm), + Optional.FromNullable(command.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + [.. domainMoodsResult.Select(moodResult => moodResult.Value)], + [.. domainIsrcsResult.Select(isrcResult => isrcResult.Value)], + [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]); + if (updateResult.IsFailure) + return updateResult.Errors; + + return artist; + } +} 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 new file mode 100644 index 00000000..3635ccf8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class UpdateTrackRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the library the track belongs to, taken from the route. + /// The Id of the artist the track belongs to, taken from the route. + /// The Id of the album the track belongs to, taken from the route. + /// The Id of the track to update, taken from the route. + /// The converted command. + public static UpdateTrackCommand ToCommand(this UpdateTrackRequest request, string? libraryId, string? artistId, string? albumId, string? trackId) + { + return new UpdateTrackCommand( + libraryId, + artistId, + albumId, + trackId, + request.Path, + request.Metadata, + request.TrackNumber, + request.DiscNumber, + request.Script, + request.Key, + request.Bpm, + request.Work, + request.MusicBrainzRecordingId, + request.MusicBrainzTrackId, + request.MusicBrainzWorkId, + request.Moods, + request.Isrcs, + request.Contributors, + request.Ratings); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index fe652e54..2e7e8142 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -56,7 +56,7 @@ public static class LibraryEntityMapping repositoryEntity.Title, repositoryEntity.LibraryType, repositoryEntity.ContentLocations.Select(contentLocation => contentLocation.Path), - repositoryEntity.CoverImage, + Optional.FromNullable(repositoryEntity.CoverImage), repositoryEntity.IsEnabled, repositoryEntity.IsLocked, repositoryEntity.CanDownloadMetadataFromWeb, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index 90f36343..be721acb 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -26,7 +26,7 @@ public static class LibraryMapping LibraryType = domainEntity.LibraryType, UserId = domainEntity.UserId.Value, ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })], - CoverImage = domainEntity.CoverImage, + CoverImage = domainEntity.CoverImage.HasValue ? domainEntity.CoverImage.Value : null, IsEnabled = domainEntity.IsEnabled, IsLocked = domainEntity.IsLocked, CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb, @@ -46,8 +46,9 @@ public static class LibraryMapping })], CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, - UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, - UpdatedBy = Guid.Empty + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null }; } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs index 6d4eb0d0..77e6f1c7 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryScanMapping.cs @@ -28,7 +28,7 @@ public static class LibraryScanMapping Library = null!, CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, - UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null, UpdatedBy = Guid.Empty }; } 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 new file mode 100644 index 00000000..ba89c298 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaContributors; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class AddBookCommandMapping +{ + /// + /// Converts to . + /// + /// The command to be converted. + /// The Id of the media library the library is added to. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this AddBookCommand command, Guid libraryId) + { + IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainEntities(); + errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; + if (errors.Count > 0) + return errors; + + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + // TODO: update Api.Books.md documentation when the functionality is fully implemented. + BookSeries? bookSeries = null; + if (command.Series != null) + { + // TODO: add logic to search the book series repository for existing book series, based on the provided title. + // TODO: uncomment integration and unit tests about series. + } + + // 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!.ToBookDomainEntities(); + errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors)]; + if (errors.Count > 0) + return errors; + + return Book.Create( + LibraryId.Create(libraryId), + command.Path!, + metadataResult.Value, + Optional.FromNullable(command.Format), + Optional.FromNullable(command.Edition), + Optional.FromNullable(command.VolumeNumber), + Optional.FromNullable(bookSeries), + Optional.FromNullable(command.ASIN), + Optional.FromNullable(command.GoodreadsId), + Optional.FromNullable(command.LCCN), + Optional.FromNullable(command.OCLCNumber), + Optional.FromNullable(command.OpenLibraryId), + Optional.FromNullable(command.LibraryThingId), + Optional.FromNullable(command.GoogleBooksId), + Optional.FromNullable(command.BarnesAndNobleId), + Optional.FromNullable(command.AppleBooksId), + [.. domainIsbnsResult.Select(isbn => isbn.Value)], + [.. domainContributorsResult.Select(domainContributor => domainContributor.Value)], + [.. domainRatingsResult.Select(domainRating => domainRating.Value)] + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs index 0db3fb9f..6ad3cdbd 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMapping.cs @@ -15,11 +15,12 @@ public static class AddBookRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library the book is added to, taken from the route. /// The converted command. - public static AddBookCommand ToCommand(this AddBookRequest request) + public static AddBookCommand ToCommand(this AddBookRequest request, string? libraryId) { return new AddBookCommand( - request.LibraryId, + libraryId, request.Path, request.Metadata, request.Format, 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 25152210..a143e43e 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 @@ -5,16 +5,17 @@ using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -59,6 +60,16 @@ public static class BookEntityMapping if (bookRatingResult.IsFailure) return bookRatingResult.Errors; + List domainContributors = []; + foreach (BookContributorEntity bookContributor in repositoryEntity.Contributors) + { + Result contributorResult = BookMediaContributor.Create( + MediaContributorId.Create(bookContributor.MediaContributorId), bookContributor.Role); + if (contributorResult.IsFailure) + return contributorResult.Errors; + domainContributors.Add(contributorResult.Value); + } + Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(repositoryEntity.OriginalReleaseDate), Optional.FromNullable(repositoryEntity.OriginalReleaseYear), @@ -71,30 +82,20 @@ public static class BookEntityMapping return releaseInfoResult.Errors; Optional languageInfo = Optional.None(); - if (repositoryEntity.LanguageCode is not null) - { - Result languageInfoResult = LanguageInfo.Create( + if (repositoryEntity.LanguageCode is not null && repositoryEntity.LanguageName is not null) + languageInfo = LanguageInfo.Create( repositoryEntity.LanguageCode, repositoryEntity.LanguageName, Optional.FromNullable(repositoryEntity.LanguageNativeName) ); - if (languageInfoResult.IsFailure) - return languageInfoResult.Errors; - languageInfo = languageInfoResult.Value; - } Optional originalLanguageCode = Optional.None(); - if (repositoryEntity.OriginalLanguageCode is not null) - { - Result originalLanguageInfoResult = LanguageInfo.Create( + if (repositoryEntity.OriginalLanguageCode is not null && repositoryEntity.OriginalLanguageName is not null) + originalLanguageCode = LanguageInfo.Create( repositoryEntity.OriginalLanguageCode, - repositoryEntity.OriginalLanguageName!, + repositoryEntity.OriginalLanguageName, Optional.FromNullable(repositoryEntity.OriginalLanguageNativeName) ); - if (originalLanguageInfoResult.IsFailure) - return originalLanguageInfoResult.Errors; - originalLanguageCode = originalLanguageInfoResult.Value; - } Result writtenContentMetadataResult = WrittenContentMetadata.Create( repositoryEntity.Title, @@ -134,7 +135,7 @@ public static class BookEntityMapping repositoryEntity.CreatedOnUtc, Optional.FromNullable(repositoryEntity.UpdatedOnUtc), [.. isbnsResult.Select(isbn => isbn.Value)], - [.. repositoryEntity.BookContributors.Select(bookContributor => MediaContributorId.Create(bookContributor.MediaContributorId))], + domainContributors, [.. bookRatingsResult.Select(bookRating => bookRating.Value)]); if (bookResult.IsFailure) return bookResult.Errors; @@ -218,14 +219,14 @@ public static class BookEntityMapping repositoryEntity.BarnesAndNobleId, repositoryEntity.AppleBooksId, [.. repositoryEntity.ISBNs.ToResponses()], - null, + [.. repositoryEntity.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], [.. repositoryEntity.Ratings.ToResponses()], repositoryEntity.MetadataStatus, repositoryEntity.LastMetadataUpdateUtc, repositoryEntity.MetadataProvider, repositoryEntity.CreatedOnUtc, repositoryEntity.UpdatedOnUtc, - repositoryEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName + repositoryEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName ); } @@ -255,46 +256,4 @@ public static class BookEntityMapping NumberOfPages = repositoryEntities.NumberOfPages }; } - - /// - /// Converts to . - /// - /// The repository entity to be converted. - /// The converted response entity. - public static BookLiteResponse ToLiteResponse(this BookEntity repositoryEntity) - { - return new BookLiteResponse( - repositoryEntity.Id, - repositoryEntity.Title, - repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear, - repositoryEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName - ); - } - - /// - /// Converts to a collection of . - /// - /// The repository entities to be converted. - /// The converted reponses. - public static IReadOnlyList ToLiteResponses(this IEnumerable repositoryEntities) - { - return [.. repositoryEntities.Select(repositoryEntity => repositoryEntity.ToLiteResponse())]; - } - - /// - /// Converts to a paginated collection of . - /// - /// The paginated repository entities to be converted. - /// The converted paginated responses. - public static PaginatedResponse ToLiteResponses(this PaginatedResultDto repositoryEntities) - { - return new PaginatedResponse - { - Data = repositoryEntities.Data.ToLiteResponses(), - CurrentPage = repositoryEntities.CurrentPage, - PerPage = repositoryEntities.PerPage, - Count = repositoryEntities.Count, - NumberOfPages = repositoryEntities.NumberOfPages - }; - } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs new file mode 100644 index 00000000..4553d134 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMapping.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class BookLiteRowMapping +{ + /// + /// Converts to . + /// + /// The read model to be converted. + /// The converted response. + public static BookLiteResponse ToResponse(this BookLiteRow readModel) + { + return new BookLiteResponse( + readModel.Id, + readModel.Title, + readModel.ReleaseYear, + readModel.CoverPath); + } + + /// + /// Converts to a collection of . + /// + /// The read models to be converted. + /// The converted responses. + public static IReadOnlyList ToResponses(this IEnumerable readModels) + { + return [.. readModels.Select(readModel => readModel.ToResponse())]; + } + + /// + /// Converts to a paginated collection of . + /// + /// The paginated read models to be converted. + /// The converted paginated responses. + public static PaginatedResponse ToResponses(this PaginatedResultDto readModels) + { + return new PaginatedResponse + { + Data = readModels.Data.ToResponses(), + CurrentPage = readModels.CurrentPage, + PerPage = readModels.PerPage, + Count = readModels.Count, + NumberOfPages = readModels.NumberOfPages + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs index 8e1edf71..37046f65 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using System; +using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -57,11 +58,22 @@ public static class BookMapping BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()], + Contributors = [.. domainEntity.Contributors.Select(contributor => new BookContributorEntity + { + Id = Guid.NewGuid(), + BookId = domainEntity.Id.Value, + MediaContributorId = contributor.ContributorId.Value, + Role = contributor.Role, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedBy = null + })], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], CreatedOnUtc = domainEntity.CreatedOnUtc, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, - UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : null, + CreatedBy = Guid.Empty, + // The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here. + UpdatedOnUtc = null, + UpdatedBy = null, }; } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs index 03593d83..ba114d4e 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs @@ -44,36 +44,32 @@ public static class BookMetadataDtoMapping return releaseInfoResult.Errors; List> domainGenresResult = metadata.Genres is not null - ? [.. metadata.Genres.Select(genre => Genre.Create(genre.Name))] + ? [.. metadata.Genres.Select(genre => Genre.Create(genre.Name!))] : []; List genresErrors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; if (genresErrors.Count != 0) return genresErrors; List> domainTagsResult = metadata.Tags is not null - ? [.. metadata.Tags.Select(tag => Tag.Create(tag.Name))] + ? [.. metadata.Tags.Select(tag => Tag.Create(tag.Name!))] : []; List tagsErrors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; if (tagsErrors.Count != 0) return tagsErrors; Optional languageInfo = Optional.None(); - if (metadata.Language is not null) - { - Result languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional.FromNullable(metadata.Language.NativeName)); - if (languageInfoResult.IsFailure) - return languageInfoResult.Errors; - languageInfo = languageInfoResult.Value; - } + if (metadata.Language is not null && metadata.Language.LanguageCode is not null && metadata.Language.LanguageName is not null) + languageInfo = LanguageInfo.Create( + metadata.Language.LanguageCode, + metadata.Language.LanguageName, + Optional.FromNullable(metadata.Language.NativeName)); Optional originalLanguageInfo = Optional.None(); - if (metadata.OriginalLanguage is not null) - { - Result originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional.FromNullable(metadata.OriginalLanguage.NativeName)); - if (originalLanguageInfoResult.IsFailure) - return originalLanguageInfoResult.Errors; - originalLanguageInfo = originalLanguageInfoResult.Value; - } + if (metadata.OriginalLanguage is not null && metadata.OriginalLanguage.LanguageCode is not null && metadata.OriginalLanguage.LanguageName is not null) + originalLanguageInfo = LanguageInfo.Create( + metadata.OriginalLanguage.LanguageCode, + metadata.OriginalLanguage.LanguageName, + Optional.FromNullable(metadata.OriginalLanguage.NativeName)); Result writtenContentMetadataResult = WrittenContentMetadata.Create( metadata.Title, @@ -91,7 +87,7 @@ public static class BookMetadataDtoMapping return writtenContentMetadataResult.Errors; List> domainIsbnsResult = metadata.Isbns is not null - ? [.. metadata.Isbns.Where(isbn => isbn.Value is not null && isbn.Format is not null).Select(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format!.Value))] + ? [.. metadata.Isbns.Where(isbn => isbn.Value is not null && isbn.Format is not null).Select(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!.Value))] : []; List isbnsErrors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (isbnsErrors.Count != 0) diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs deleted file mode 100644 index 5a6445bc..00000000 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System; -#endregion - -namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Extension methods for converting . -/// -public static class GetBookRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetBookQuery ToQuery(this GetBookRequest request) - { - return new GetBookQuery( - Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs index 8635f179..8db47b81 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs @@ -16,26 +16,26 @@ public static class GetBooksLiteRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library whose books are retrieved, taken from the route. /// The converted query. - public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request) + public static GetBooksLiteQuery ToQuery(this GetBooksLiteRequest request, string? libraryId) { PaginationDataDto? paginationData = null; if (request.CurrentPage is not null || request.PerPage is not null) - { paginationData = new PaginationDataDto { CurrentPage = request.CurrentPage ?? 1, PerPage = request.PerPage ?? 200 }; - } - LibraryFilterDto libraryFilter = new() - { - LibraryId = request.LibraryId, - SearchTerm = request.SearchTerm, - FilterAlphaKey = request.FilterAlphaKey, - ShouldIgnoreThePrefixForAlphaPicker = request.ShouldIgnoreThePrefixForAlphaPicker - }; - return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); + return new GetBooksLiteQuery( + libraryId, + paginationData, + request.SearchTerm, + request.FilterAlphaKey, + request.ShouldIgnoreThePrefixForAlphaPicker, + request.SortBy, + request.SortOrder + ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs index a1f6b92f..be96f193 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMapping.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -16,8 +15,9 @@ public static class GetBooksRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library whose books are retrieved, taken from the route. /// The converted query. - public static GetBooksQuery ToQuery(this GetBooksRequest request) + public static GetBooksQuery ToQuery(this GetBooksRequest request, string? libraryId) { PaginationDataDto? paginationData = null; if (request.CurrentPage is not null || request.PerPage is not null) @@ -27,12 +27,6 @@ public static class GetBooksRequestMapping PerPage = request.PerPage ?? 200 }; - LibraryFilterDto libraryFilter = new() - { - LibraryId = request.LibraryId, - SearchTerm = request.SearchTerm - }; - - return new GetBooksQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); + return new GetBooksQuery(libraryId, paginationData, request.SearchTerm, request.SortBy, request.SortOrder); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs deleted file mode 100644 index 4737e11e..00000000 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -#endregion - -namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Extension methods for converting . -/// -public static class GetReadingAvailabilityRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetReadingAvailabilityQuery ToQuery(this GetReadingAvailabilityRequest request) - { - return new GetReadingAvailabilityQuery( - request.BookId - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs deleted file mode 100644 index 79e512c9..00000000 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -#endregion - -namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Extension methods for converting . -/// -public static class GetReadingManifestRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetReadingManifestQuery ToQuery(this GetReadingManifestRequest request) - { - return new GetReadingManifestQuery( - request.BookId - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs deleted file mode 100644 index 68b5927c..00000000 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -#endregion - -namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Extension methods for converting . -/// -public static class GetReadingResourceRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetReadingResourceQuery ToQuery(this GetReadingResourceRequest request) - { - return new GetReadingResourceQuery( - request.BookId, - request.ResourceKey - ); - } -} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs deleted file mode 100644 index 6ed66d56..00000000 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -#endregion - -namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Extension methods for converting . -/// -public static class GetReadingSectionRequestMapping -{ - /// - /// Converts to . - /// - /// The request to be converted. - /// The converted query. - public static GetReadingSectionQuery ToQuery(this GetReadingSectionRequest request) - { - return new GetReadingSectionQuery( - request.BookId, - request.LocationRef - ); - } -} 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 82de4c1c..40e63a13 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 @@ -1,6 +1,19 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaContributors; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Linq; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -11,40 +24,66 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B public static class UpdateBookCommandMapping { /// - /// Converts to , so that the edited data can be applied to the domain book. + /// Converts to , preserving the identity and creation metadata of the stored book identified by . /// - /// The command containing the edited data of the book. - /// The built metadata. - public static BookMetadataDto ToBookMetadataDto(this UpdateBookCommand command) + /// The command to be converted. + /// The stored book whose identity, file system path and creation metadata are preserved. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this UpdateBookCommand command, BookEntity existingBook) { - return new BookMetadataDto( - Title: command.Metadata!.Title, - OriginalTitle: command.Metadata.OriginalTitle, - Description: command.Metadata.Description, - ReleaseInfo: command.Metadata.ReleaseInfo, - Genres: command.Metadata.Genres, - Tags: command.Metadata.Tags, - Language: command.Metadata.Language, - OriginalLanguage: command.Metadata.OriginalLanguage, - Publisher: command.Metadata.Publisher, - PageCount: command.Metadata.PageCount, - Format: command.Format, - Edition: command.Edition, - VolumeNumber: command.VolumeNumber, - Series: command.Series, - ASIN: command.ASIN, - GoodreadsId: command.GoodreadsId, - LCCN: command.LCCN, - OCLCNumber: command.OCLCNumber, - OpenLibraryId: command.OpenLibraryId, - LibraryThingId: command.LibraryThingId, - GoogleBooksId: command.GoogleBooksId, - BarnesAndNobleId: command.BarnesAndNobleId, - AppleBooksId: command.AppleBooksId, - Isbns: command.ISBNs, - Contributors: command.Contributors, - Ratings: command.Ratings, - CoverImagePath: null + IEnumerable> domainRatingsResult = command.Ratings!.ToDomainEntities(); + List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainIsbnsResult = command.ISBNs!.ToDomainEntities(); + errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; + if (errors.Count > 0) + return errors; + + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + // TODO: update Api.Books.md documentation when the functionality is fully implemented. + BookSeries? bookSeries = null; + if (command.Series != null) + { + // TODO: add logic to search the book series repository for existing book series, based on the provided title. + // TODO: uncomment integration and unit tests about series. + } + + // 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!.ToBookDomainEntities(); + errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors)]; + if (errors.Count > 0) + return errors; + + return Book.Create( + BookId.Create(existingBook.Id), + LibraryId.Create(existingBook.LibraryId), + existingBook.Path, + metadataResult.Value, + Optional.FromNullable(command.Format), + Optional.FromNullable(command.Edition), + Optional.FromNullable(command.VolumeNumber), + Optional.FromNullable(bookSeries), + Optional.FromNullable(command.ASIN), + Optional.FromNullable(command.GoodreadsId), + Optional.FromNullable(command.LCCN), + Optional.FromNullable(command.OCLCNumber), + Optional.FromNullable(command.OpenLibraryId), + Optional.FromNullable(command.LibraryThingId), + Optional.FromNullable(command.GoogleBooksId), + Optional.FromNullable(command.BarnesAndNobleId), + Optional.FromNullable(command.AppleBooksId), + existingBook.CreatedOnUtc, + Optional.FromNullable(existingBook.UpdatedOnUtc), + [.. domainIsbnsResult.Select(isbn => isbn.Value)], + [.. domainContributorsResult.Select(domainContributor => domainContributor.Value)], + [.. domainRatingsResult.Select(domainRating => domainRating.Value)] ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMapping.cs new file mode 100644 index 00000000..f28821d0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMapping.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Extension methods for converting . +/// +public static class UpdateBookCoverCommandMapping +{ + /// + /// Converts to the cover artwork of the book identified by , replacing the + /// file of when the book already has a cover, or creating a new cover artwork when it does not. + /// + /// The command whose cover image was stored. + /// The existing cover artwork of the book, or when the book has none. + /// The Id of the book the cover belongs to. + /// The relative path of the stored cover image. + /// The Id of the user that stored the cover image. + /// The cover artwork of the book, carrying the stored cover image. + public static BookArtworkEntity ToRepositoryEntity(this UpdateBookCoverCommand command, BookArtworkEntity? existingCover, Guid bookId, string storedCoverPath, Guid userId) + { + if (existingCover is null) + { + return new BookArtworkEntity + { + Id = Guid.NewGuid(), + BookId = bookId, + ArtworkType = ArtworkType.Cover, + Ordinal = 0, + FileName = storedCoverPath, + Status = ArtworkStatus.Enriched, + CreatedOnUtc = DateTime.UtcNow, + CreatedBy = userId, + UpdatedBy = null + }; + } + + existingCover.FileName = storedCoverPath; + existingCover.Status = ArtworkStatus.Enriched; + existingCover.LastUpdateUtc = DateTime.UtcNow; + existingCover.UpdatedOnUtc = DateTime.UtcNow; + existingCover.UpdatedBy = userId; + return existingCover; + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs index 6720e145..25b2dd97 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestMapping.cs @@ -15,11 +15,14 @@ public static class UpdateBookRequestMapping /// Converts to . /// /// The request to be converted. + /// The Id of the library the book belongs to, taken from the route. + /// The Id of the book to update, taken from the route. /// The converted command. - public static UpdateBookCommand ToCommand(this UpdateBookRequest request) + public static UpdateBookCommand ToCommand(this UpdateBookRequest request, string? libraryId, string? bookId) { return new UpdateBookCommand( - Guid.TryParse(request.Id, out Guid bookId) ? bookId : Guid.Empty, + libraryId, + bookId, request.Metadata, request.Format, request.Edition, 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 228e0d3d..359effde 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 @@ -24,7 +24,7 @@ public static class IsbnDtoMapping public static Result ToDomainEntity(this IsbnDto dto) { return Isbn.Create( - dto.Value, + dto.Value!, dto.Format ?? IsbnFormat.Isbn13 ); } 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 d5e1645b..f4998385 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 @@ -47,7 +47,7 @@ public static class IsbnEntityMapping public static Result ToDomainEntity(this IsbnEntity repositoryEntity) { return Isbn.Create( - repositoryEntity.Value ?? default, + repositoryEntity.Value!, repositoryEntity.Format ?? default ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs new file mode 100644 index 00000000..931e66c5 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common; + +/// +/// Extension methods for converting . +/// +public static class WrittenContentMetadataDtoMapping +{ + /// + /// Converts to . + /// + /// The DTO to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this WrittenContentMetadataDto dto) + { + + Result? domainReleaseInfoResult = dto.ReleaseInfo!.ToDomainEntity(); + if (domainReleaseInfoResult.Value.IsFailure) + return domainReleaseInfoResult.Value.Errors; + + IEnumerable> domainGenresResult = dto.Genres!.ToDomainEntities(); + List errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainTagsResult = dto.Tags!.ToDomainEntities(); + errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; + if (errors.Count > 0) + return errors; + + Result? domainLanguageInfoResult = dto.Language?.ToDomainEntity(); + if (domainLanguageInfoResult.HasValue && domainLanguageInfoResult.Value.IsFailure) + return domainLanguageInfoResult.Value.Errors; + + Result? domainOriginalLanguageInfoResult = dto.OriginalLanguage?.ToDomainEntity(); + if (domainOriginalLanguageInfoResult.HasValue && domainOriginalLanguageInfoResult.Value.IsFailure) + return domainOriginalLanguageInfoResult.Value.Errors; + + return WrittenContentMetadata.Create( + dto.Title!, + Optional.FromNullable(dto.OriginalTitle), + Optional.FromNullable(dto.Description), + domainReleaseInfoResult!.Value.Value, + [.. domainGenresResult.Select(genre => genre.Value)], + [.. domainTagsResult.Select(tag => tag.Value)], + Optional.FromNullable(domainLanguageInfoResult?.Value), + Optional.FromNullable(domainOriginalLanguageInfoResult?.Value), + Optional.FromNullable(dto.Publisher), + Optional.FromNullable(dto.PageCount) + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs index 23734cb6..a2dd9855 100644 --- a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobEntityMapping.cs @@ -77,6 +77,36 @@ public static class ScheduledJobEntityMapping ); } + /// + /// Converts to a copy that carries the provided status and execution timestamps. + /// + /// The repository entity to be converted. + /// The status to assign to the converted entity. + /// The last start time to assign to the converted entity. + /// The last completion time to assign to the converted entity. + /// The converted repository entity. + public static ScheduledJobEntity ToUpdatedRepositoryEntity(this ScheduledJobEntity repositoryEntity, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) + { + return new ScheduledJobEntity + { + Id = repositoryEntity.Id, + Name = repositoryEntity.Name, + TaskType = repositoryEntity.TaskType, + ScheduleType = repositoryEntity.ScheduleType, + IntervalMinutes = repositoryEntity.IntervalMinutes, + Hour = repositoryEntity.Hour, + Minute = repositoryEntity.Minute, + Status = status, + OwnerUserId = repositoryEntity.OwnerUserId, + LastStartedOnUtc = lastStartedOnUtc, + LastCompletedOnUtc = lastCompletedOnUtc, + CreatedOnUtc = repositoryEntity.CreatedOnUtc, + CreatedBy = repositoryEntity.CreatedBy, + UpdatedOnUtc = repositoryEntity.UpdatedOnUtc, + UpdatedBy = repositoryEntity.UpdatedBy + }; + } + /// /// Creates the schedule of from its flattened schedule properties. /// diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs index 2ac77c66..5883d056 100644 --- a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobExecutionEntityMapping.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Contracts.Responses.Scheduling; +using System; #endregion namespace Lumina.Application.Common.Mapping.Scheduling; @@ -26,4 +27,28 @@ public static class ScheduledJobExecutionEntityMapping repositoryEntity.CompletedOnUtc ); } + + /// + /// Converts to a copy that carries the provided completion time. + /// + /// The repository entity to be converted. + /// The completion time to assign to the converted entity. + /// The converted repository entity. + public static ScheduledJobExecutionEntity ToUpdatedRepositoryEntity(this ScheduledJobExecutionEntity repositoryEntity, DateTime? completedOnUtc) + { + return new ScheduledJobExecutionEntity + { + Id = repositoryEntity.Id, + ScheduledJobId = repositoryEntity.ScheduledJobId, + TaskType = repositoryEntity.TaskType, + IsCycleRun = repositoryEntity.IsCycleRun, + WasCycleActive = repositoryEntity.WasCycleActive, + StartedOnUtc = repositoryEntity.StartedOnUtc, + CompletedOnUtc = completedOnUtc, + CreatedOnUtc = repositoryEntity.CreatedOnUtc, + CreatedBy = repositoryEntity.CreatedBy, + UpdatedOnUtc = repositoryEntity.UpdatedOnUtc, + UpdatedBy = repositoryEntity.UpdatedBy + }; + } } diff --git a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs index 3099ea14..753b57e8 100644 --- a/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs +++ b/src/Lumina.Application/Common/Mapping/Scheduling/ScheduledJobMapping.cs @@ -35,7 +35,7 @@ public static class ScheduledJobMapping LastCompletedOnUtc = domainEntity.LastCompletedOnUtc.HasValue ? domainEntity.LastCompletedOnUtc.Value : null, CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, - UpdatedOnUtc = domainEntity.UpdatedOnUtc, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null, UpdatedBy = Guid.Empty }; } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs index 977992b9..3ea703dc 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs @@ -1,14 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Threading; @@ -49,17 +50,17 @@ public class GetPermissionsQueryHandler : IQueryHandler public async Task>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can see the list of authorization permissions + // Only admins can see the list of authorization permissions. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getPermissionsResult.Match(value => Result.From(value.ToResponses()), errors => errors); + Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + return getPermissionsResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs index 82d1ba69..aeeaf41e 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs @@ -58,18 +58,18 @@ public class AddRoleCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can create authorization roles + // Only admins can create authorization roles. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // create the new role, with its permissions + // Create the new role, with its permissions. RoleEntity newRole = new() { RoleName = request.RoleName, @@ -81,12 +81,16 @@ public class AddRoleCommandHandler : ICommandHandler insertRoleResult = await _unitOfWork.RoleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false); if (insertRoleResult.IsFailure) return insertRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // retrieve the newly saved authorization role from the persistence medium and return it + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Retrieve the newly saved authorization role from the persistence medium and return it. Result getRoleResult = await _unitOfWork.RoleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs index c330ce1a..8363bb3a 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs @@ -1,20 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; -using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; -using Lumina.Application.Common.Mapping.Authorization; -using Lumina.Application.Common.Infrastructure.Authorization; #endregion namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; @@ -56,7 +52,7 @@ public class DeleteRoleCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; @@ -67,19 +63,24 @@ public class DeleteRoleCommandHandler : ICommandHandler getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + // Check if a role with the requested Id exists. + Result getExistingRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getExistingRoleResult.IsFailure) return getExistingRoleResult.Errors; else if (getExistingRoleResult.Value is null) return Errors.Authorization.RoleNotFound; else if (getExistingRoleResult.Value.RoleName == "Admin") return Errors.Authorization.AdminRoleCannotBeDeleted; - // delete the role and its permissions + + // Delete the role and its permissions. Result deleteRoleResult = await _unitOfWork.RoleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); if (deleteRoleResult.IsFailure) return deleteRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return deleteRoleResult.Value; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; } } diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs index a5d4cc94..e97a5cd1 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -10,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; @@ -58,37 +57,41 @@ public class UpdateRoleCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can update authorization roles + // Only admins can update authorization roles. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // update the role and its permissions + // Update the role and its permissions. RoleEntity newRole = new() { Id = command.RoleId, RoleName = command.RoleName, - RolePermissions = command.Permissions.Select(permissionId => new RolePermissionEntity() + RolePermissions = [.. command.Permissions.Select(permissionId => new RolePermissionEntity() { PermissionId = permissionId, Permission = null!, Role = null!, RoleId = default - }).ToList() + })] }; - // save the updated role in the repository + // Save the updated role in the repository. Result updateRoleResult = await _unitOfWork.RoleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false); if (updateRoleResult.IsFailure) return updateRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // retrieve the updated authorization role from the persistence medium and return it - Result getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Retrieve the updated authorization role from the persistence medium and return it. + Result getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; if (getRoleResult.Value is null) diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs index 59920ec7..c428ffd5 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; @@ -10,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Threading; @@ -57,18 +57,19 @@ public class GetRolePermissionsQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can see the list of authorization roles + // Only admins can see the list of authorization roles. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // get the role from the repository and return its role permissions - Result getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false); + + // Get the role from the repository and return its role permissions. + Result getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure) return getRoleResult.Errors; else if (getRoleResult.Value is null) diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs index db595254..1cd48b58 100644 --- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs +++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs @@ -1,14 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Authorization; using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Threading; @@ -49,17 +51,18 @@ public class GetRolesQueryHandler : IQueryHandler public async Task>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can see the list of authorization roles + // Only admins can see the list of authorization roles. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - Result> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors); + + Result> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + return getRolesResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs index 86da3e1c..8bfa3b38 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs @@ -9,9 +9,9 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi /// Query for retrieving the list of directories at a path. /// /// The path for which to retrieve the list of directories. -/// Whether to include hidden directories or not. +/// Whether to include hidden directories or not. [DebuggerDisplay("Path: {Path}")] public record GetDirectoriesQuery( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs index 50461153..8c44110a 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs @@ -46,7 +46,7 @@ public class GetDirectoriesQueryHandler : IQueryHandler 0) return Task.FromResult>>(validationResult); - Result> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements); + Result> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.ShouldIncludeHiddenElements); return Task.FromResult(getSubdirectoriesResult.Match(values => Result.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs index b5351d79..6f6e823e 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQuery.cs @@ -9,9 +9,9 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles; /// Query for retrieving the list of files at a path. /// /// The path for which to retrieve the list of files. -/// Whether to include hidden files and directories or not. +/// Whether to include hidden files and directories or not. [DebuggerDisplay("Path: {Path}")] public record GetFilesQuery( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs index 5718613e..dfed7239 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandler.cs @@ -46,7 +46,7 @@ public class GetFilesQueryHandler : IQueryHandler 0) return Task.FromResult>>(validationResult); - Result> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); + Result> getFilesResult = _fileService.GetFiles(query.Path!, query.ShouldIncludeHiddenElements); return Task.FromResult(getFilesResult.Match(values => Result.From(values.ToResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs index 452debc6..73d0b124 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQuery.cs @@ -9,9 +9,9 @@ namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFile /// Query for retrieving the list of files at a path. /// /// The path for which to retrieve the list of files. -/// Whether to include hidden files and directories or not. +/// Whether to include hidden files and directories or not. [DebuggerDisplay("Path: {Path}")] public record GetTreeFilesQuery( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs index 586660e2..5360735e 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandler.cs @@ -46,7 +46,7 @@ public class GetTreeFilesQueryHandler : IQueryHandler 0) return Task.FromResult>>(validationResult); - Result> getFilesResult = _fileService.GetFiles(query.Path!, query.IncludeHiddenElements); + Result> getFilesResult = _fileService.GetFiles(query.Path!, query.ShouldIncludeHiddenElements); return Task.FromResult(getFilesResult.Match(values => Result.From(values.ToFileSystemTreeNodeResponses()), errors => errors)); } } diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs index 02ce1e37..95d8c79a 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQuery.cs @@ -9,9 +9,9 @@ namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathEx /// Query for checking the existence of a file system path. /// /// The path for which to check the existence of. -/// Whether to include hidden file system elements or not. -[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] +/// Whether to include hidden file system elements or not. +[DebuggerDisplay("Path: {Path}, ShouldIncludeHiddenElements: {ShouldIncludeHiddenElements}")] public record CheckPathExistsQuery( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ) : IQuery; diff --git a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs index 8e90b042..f83caf6c 100644 --- a/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs +++ b/src/Lumina.Application/Core/FileSystemManagement/Paths/Queries/CheckPathExists/CheckPathExistsQueryHandler.cs @@ -44,6 +44,6 @@ public class CheckPathExistsQueryHandler : IQueryHandler 0) return Task.FromResult>(validationResult); - return Task.FromResult(Result.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.IncludeHiddenElements)))); + return Task.FromResult(Result.From(new PathExistsResponse(_pathService.Exists(query.Path!, query.ShouldIncludeHiddenElements)))); } } diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs index 47a8a836..6b74fee9 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Commands/SetupApplication/SetupApplicationCommandHandler.cs @@ -1,18 +1,19 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Contracts.Responses.Authentication; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; @@ -89,12 +90,12 @@ public class SetupApplicationCommandHandler : ICommandHandler> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (selectUsersResult.IsFailure) return selectUsersResult.Errors; - else if (selectUsersResult.Value.Any()) + else if (selectUsersResult.Value.Data.Any()) return Errors.Authorization.AdminAccountAlreadyCreated; - // no users are present, register the admin one + // No users are present, register the admin one. string? totpSecret = null; Guid id = Guid.NewGuid(); UserEntity user = new() @@ -123,7 +124,9 @@ public class SetupApplicationCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Set the default permissions, roles, roles permissions. Result setPermissionsResult = await _dataSeedService.SetDefaultAuthorizationPermissionsAsync(id, cancellationToken).ConfigureAwait(false); @@ -150,15 +153,15 @@ public class SetupApplicationCommandHandler : ICommandHandler> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) return getScheduledJobsResult.Errors; - foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value) + foreach (ScheduledJobEntity scheduledJob in getScheduledJobsResult.Value.Data) if (scheduledJob.Status == ScheduledJobStatus.Active) _domainEventsQueue.Enqueue(new ScheduledJobCycleStartedDomainEvent(Guid.NewGuid(), ScheduledJobId.Create(scheduledJob.Id), DateTime.UtcNow)); // TODO: insert the default admin profile preferences when they are implemented. - // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed + // If 2FA was enabled during registration, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed. return new RegistrationResponse(user.Id, user.Username, totpSecret); } } diff --git a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs index 8f2dba4c..3d647435 100644 --- a/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs +++ b/src/Lumina.Application/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandler.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Contracts.Responses.UsersManagement; -using System.Collections.Generic; +using Lumina.Domain.Common.Primitives; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -38,10 +38,10 @@ public class CheckInitializationQueryHandler : IQueryHandler public async Task HandleAsync(CheckInitializationQuery query, CancellationToken cancellationToken) { - // if the repository reports an error, or there are no users, the application has not been initialized - Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken); + // If the repository reports an error, or there are no users, the application has not been initialized. + Result> selectUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken); if (!selectUsersResult.IsFailure) - return new InitializationResponse(selectUsersResult.Value.Any()); + return new InitializationResponse(selectUsersResult.Value.Data.Any()); return new InitializationResponse(false); } } 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 new file mode 100644 index 00000000..8a0a0f38 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; + +/// +/// Command for adding an album to an artist. +/// +/// The unique identifier of the media library this album belongs to, taken from the route. +/// 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 barcode of the album, if applicable. +/// The catalog 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. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record AddAlbumCommand( + string? LibraryId, + string? ArtistId, + AlbumMetadataDto? Metadata, + MusicMediaFormat? MediaFormat, + string? Barcode, + string? CatalogNumber, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + List? Contributors, + List? Ratings, + List? Tracks, + Guid? AlbumId = null +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandler.cs new file mode 100644 index 00000000..ad5ea530 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandler.cs @@ -0,0 +1,201 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +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.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; + +/// +/// Handler for the command to add an album to an artist. +/// +public class AddAlbumCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + /// Injected service for file system path related functionality. + public AddAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + _pathService = pathService; + } + + /// + /// Handles the command to add an album to an artist. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async Task> HandleAsync(AddAlbumCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + + // An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is added within it. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the album must belong to an artist of the library named by the route, so that an album can never be added through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can add albums to the artists of all libraries; for everyone else, only to the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // An album can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // An album's tracks are only readable if they are stored inside one of the content locations of their library, so a client can never + // register an entry that points the reading pipeline at an arbitrary file of the host. + if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command)) + return DomainErrors.Music.TrackPathMustBeWithinLibraryContentLocations; + + // Media contributors are referenced by Id and are never created implicitly by adding an album, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + + // The write path goes through the aggregate root: an album is a child entity of the artist aggregate, unlike Book and Artist, + // which are aggregate roots and are created directly with their own Create method. This difference is intentional. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + + Result createAlbumResult = command.ToDomainEntity(); + if (createAlbumResult.IsFailure) + return createAlbumResult.Errors; + Result addAlbumResult = artistResult.Value.AddAlbum(createAlbumResult.Value); + if (addAlbumResult.IsFailure) + return addAlbumResult.Errors; + + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Reading does not need the aggregate: the album is read directly and mapped to the response. + Result getPersistedAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(createAlbumResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedAlbumResult.IsFailure) + return getPersistedAlbumResult.Errors; + if (getPersistedAlbumResult.Value is null) + return DomainErrors.Music.AlbumNotFound; + + return getPersistedAlbumResult.Value.ToResponse(); + } + + /// + /// Determines whether every track path referenced by is stored inside one of the content locations of . + /// + /// The media library that owns the album. + /// The command carrying the referenced tracks. + /// when every referenced track path is within a content location of the library; otherwise, . + private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, AddAlbumCommand command) + { + foreach (AddTrackCommand track in command.Tracks!) + if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path!, contentLocation.Path))) + return false; + return true; + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(AddAlbumCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. CollectContributorIds(command).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return DomainErrors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); + } + + /// + /// Collects the unique identifiers of every media contributor referenced by , be it directly on the album, + /// or indirectly through one of its tracks. + /// + /// The command carrying the referenced media contributors. + /// The collected media contributor identifiers. + private static IEnumerable CollectContributorIds(AddAlbumCommand command) + { + foreach (MediaContributorReferenceDto contributor in command.Contributors!) + yield return contributor.ContributorId; + + foreach (AddTrackCommand track in command.Tracks!) + foreach (MediaContributorReferenceDto contributor in track.Contributors!) + yield return contributor.ContributorId; + } +} 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 new file mode 100644 index 00000000..9dc0f385 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs @@ -0,0 +1,540 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; + +/// +/// Validates the needed validation rules for . +/// +public class AddAlbumCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddAlbumCommandValidator() + { + // Validates the identifier of the media library that owns the album, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album is added to, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the metadata of the album: title, lengths, release type and status, disc and track counts, release information, languages, genres and tags. + RuleFor(command => command.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.AlbumTitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleFor(m => m!.ReleaseType) + .IsInEnum() + .When(m => m!.ReleaseType is not null) + .WithError(Errors.Music.UnknownMusicReleaseType); + + metadata.RuleFor(m => m!.ReleaseStatus) + .IsInEnum() + .When(m => m!.ReleaseStatus is not null) + .WithError(Errors.Music.UnknownMusicReleaseStatus); + + metadata.RuleFor(m => m!.TotalDiscs) + .GreaterThan(0) + .When(m => m!.TotalDiscs.HasValue) + .WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.TotalTracks) + .GreaterThan(0) + .When(m => m!.TotalTracks.HasValue) + .WithError(Errors.Music.TotalTracksMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + 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)); + + metadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the physical characteristics of the album: format and catalog number. + RuleFor(command => command.MediaFormat) + .IsInEnum() + .When(command => command.MediaFormat is not null) + .WithError(Errors.Music.UnknownMusicMediaFormat); + + RuleFor(command => command.CatalogNumber) + .MaximumLength(50) + .When(command => command.CatalogNumber is not null) + .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + + RuleFor(command => command.Barcode) + .NotEmpty() + .When(command => command.Barcode is not null) + .WithError(Errors.Music.BarcodeValueCannotBeEmpty); + + RuleFor(command => command.Barcode) + .Matches(@"^\d{12,13}$") + .When(command => command.Barcode is not null && command.Barcode.Length > 0) + .WithError(Errors.Music.InvalidFormatForBarcode); + + RuleFor(command => command.MusicBrainzReleaseId) + .Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty) + .When(command => command.MusicBrainzReleaseId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + RuleFor(command => command.MusicBrainzReleaseGroupId) + .Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty) + .When(command => command.MusicBrainzReleaseGroupId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + RuleFor(command => command.MusicBrainzReleaseArtistId) + .Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty) + .When(command => command.MusicBrainzReleaseArtistId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + // Validates the media contributors that performed on the album. + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the album. + 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 the tracks of the album. + RuleFor(command => command.Tracks) + .NotNull() + .WithError(Errors.Music.TracksListCannotBeNull); + + RuleForEach(command => command.Tracks) + .ChildRules(track => + { + // Validates the file system path of the track. + track.RuleFor(t => t!.Path) + .NotEmpty() + .WithError(Errors.Music.TrackPathCannotBeEmpty) + .MaximumLength(2048) + .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + + // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. + track.RuleFor(t => t!.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(trackMetadata => + { + trackMetadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + trackMetadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + trackMetadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the MusicBrainz identifiers of the track. + track.RuleFor(t => t!.MusicBrainzRecordingId) + .Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty) + .When(t => t!.MusicBrainzRecordingId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + track.RuleFor(t => t!.MusicBrainzTrackId) + .Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty) + .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() + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.TrackNumber) + .GreaterThan(0) + .When(t => t!.TrackNumber.HasValue) + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.DiscNumber) + .GreaterThan(0) + .When(t => t!.DiscNumber.HasValue) + .WithError(Errors.Music.DiscNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.Script) + .MaximumLength(50) + .When(t => t!.Script is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + track.RuleFor(t => t!.Key) + .IsInEnum() + .When(t => t!.Key is not null) + .WithError(Errors.Music.UnknownMusicKey); + + track.RuleFor(t => t!.Bpm) + .GreaterThan(0) + .When(t => t!.Bpm.HasValue) + .WithError(Errors.Music.BpmMustBeGreaterThanZero); + + track.RuleFor(t => t!.Work) + .MaximumLength(255) + .When(t => t!.Work is not null) + .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + + // Validates the media contributors that performed on the track. + track.RuleFor(t => t!.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + track.RuleForEach(t => t!.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the moods and the ISRC codes of the track. + track.RuleForEach(t => t!.Moods) + .ChildRules(mood => + mood.RuleFor(m => m.Name) + .NotEmpty() + .WithError(Errors.Metadata.MoodNameCannotBeEmpty)); + + track.RuleForEach(t => t!.Isrcs) + .ChildRules(isrc => + isrc.RuleFor(i => i.Value) + .NotEmpty() + .WithError(Errors.Music.IsrcValueCannotBeEmpty)); + + // Validates the ratings of the track. + track.RuleFor(t => t!.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + track.RuleForEach(t => t!.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); + }); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommand.cs new file mode 100644 index 00000000..f15c5e70 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; + +/// +/// Command for deleting an album by its Id. +/// +/// The unique identifier of the media library this album belongs to, taken from the route. +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album to delete, taken from the route. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record DeleteAlbumCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs new file mode 100644 index 00000000..3c63ada0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; + +/// +/// Handler for the command to delete an album by its Id. +/// +public class DeleteAlbumCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public DeleteAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to delete an album by its Id. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(DeleteAlbumCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + + // An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is removed within it. + Result getArtistResult = await _unitOfWork.ArtistRepository + .GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the album must belong to an artist of the library named by the route, so that an album can never be deleted through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can delete the albums of all libraries; for everyone else, only the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId); + if (existingAlbum is null) + return DomainErrors.Music.AlbumNotFound; + + // An album can only belong to a library that exists, so a client can never delete an album of a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // The write path goes through the aggregate root: an album is a child entity of the artist aggregate, unlike Book and Artist, + // which are aggregate roots and are deleted directly through their own repositories. This difference is intentional. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + // The album is an entity inside the artist aggregate, so it is referenced by object, not by id; the aggregate member is located here and passed through. + Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId); + if (domainAlbum is null) + return DomainErrors.Music.AlbumNotFound; + Result removeAlbumResult = artistResult.Value.RemoveAlbum(domainAlbum); + if (removeAlbumResult.IsFailure) + return removeAlbumResult.Errors; + + Result updateResult = await _unitOfWork.ArtistRepository + .UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidator.cs new file mode 100644 index 00000000..ed1c7c14 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidator.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteAlbumCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteAlbumCommandValidator() + { + // Validates the identifier of the media library that owns the album, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album belongs to, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album to delete, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs new file mode 100644 index 00000000..d31323ff --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; + +/// +/// Command for updating an album. +/// +/// The unique identifier of the media library this album belongs to, taken from the route. +/// The unique identifier of the artist this album belongs to, taken from the route. +/// 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 barcode of the album, if applicable. +/// The catalog 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. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateAlbumCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId, + AlbumMetadataDto? Metadata, + MusicMediaFormat? MediaFormat, + string? Barcode, + string? CatalogNumber, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + List? Contributors, + List? Ratings +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandler.cs new file mode 100644 index 00000000..e847c9eb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandler.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary; +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.Artists; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +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; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; + +/// +/// Handler for the command to update an album. +/// +public class UpdateAlbumCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public UpdateAlbumCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to update an album. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully updated , or an error message. + /// + public async Task> HandleAsync(UpdateAlbumCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + + // An album is a child of the artist aggregate, so the whole aggregate is loaded and the album is edited within it. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the album must belong to an artist of the library named by the route, so that an album can never be edited through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return Errors.Music.ArtistNotFound; + + // Admins can update the albums of all libraries; for everyone else, only the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId); + if (existingAlbum is null) + return Errors.Music.AlbumNotFound; + + // An album can only belong to a library that exists, so a client can never update an album of a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + + // Media contributors are referenced by Id and are never created implicitly by editing an album, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + + // The write path goes through the aggregate root: an album is a child entity of the artist aggregate, so it is mutated through its owning + // artist. Book is itself an aggregate root, so its update flow reconstitutes it directly with its own Create method instead. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + + Result updateAlbumResult = command.ToDomainEntity(artistResult.Value); + if (updateAlbumResult.IsFailure) + return updateAlbumResult.Errors; + + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(updateAlbumResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Reading does not need the aggregate: the album is read directly and mapped to the response. + Result getPersistedAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedAlbumResult.IsFailure) + return getPersistedAlbumResult.Errors; + if (getPersistedAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + + return getPersistedAlbumResult.Value.ToResponse(); + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(UpdateAlbumCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. CollectContributorIds(command).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return Errors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); + } + + /// + /// Collects the unique identifiers of every media contributor referenced by . + /// + /// The command carrying the referenced media contributors. + /// The collected media contributor identifiers. + private static IEnumerable CollectContributorIds(UpdateAlbumCommand command) + { + foreach (MediaContributorReferenceDto contributor in command.Contributors!) + yield return contributor.ContributorId; + } + +} 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 new file mode 100644 index 00000000..48fa09ff --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs @@ -0,0 +1,288 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateAlbumCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumCommandValidator() + { + // Validates the identifier of the media library that owns the album, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist that owns the album, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the metadata of the album: title, lengths, release type and status, disc and track counts, release information, languages, genres and tags. + RuleFor(command => command.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.AlbumTitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleFor(m => m!.ReleaseType) + .IsInEnum() + .When(m => m!.ReleaseType is not null) + .WithError(Errors.Music.UnknownMusicReleaseType); + + metadata.RuleFor(m => m!.ReleaseStatus) + .IsInEnum() + .When(m => m!.ReleaseStatus is not null) + .WithError(Errors.Music.UnknownMusicReleaseStatus); + + metadata.RuleFor(m => m!.TotalDiscs) + .GreaterThan(0) + .When(m => m!.TotalDiscs.HasValue) + .WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.TotalTracks) + .GreaterThan(0) + .When(m => m!.TotalTracks.HasValue) + .WithError(Errors.Music.TotalTracksMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + 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)); + + metadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the physical characteristics of the album: format and catalog number. + RuleFor(command => command.MediaFormat) + .IsInEnum() + .When(command => command.MediaFormat is not null) + .WithError(Errors.Music.UnknownMusicMediaFormat); + + RuleFor(command => command.CatalogNumber) + .MaximumLength(50) + .When(command => command.CatalogNumber is not null) + .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + + RuleFor(command => command.Barcode) + .NotEmpty() + .When(command => command.Barcode is not null) + .WithError(Errors.Music.BarcodeValueCannotBeEmpty); + + RuleFor(command => command.Barcode) + .Matches(@"^\d{12,13}$") + .When(command => command.Barcode is not null && command.Barcode.Length > 0) + .WithError(Errors.Music.InvalidFormatForBarcode); + + RuleFor(command => command.MusicBrainzReleaseId) + .Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty) + .When(command => command.MusicBrainzReleaseId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + RuleFor(command => command.MusicBrainzReleaseGroupId) + .Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty) + .When(command => command.MusicBrainzReleaseGroupId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + RuleFor(command => command.MusicBrainzReleaseArtistId) + .Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty) + .When(command => command.MusicBrainzReleaseArtistId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + // Validates the media contributors that performed on the album. + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the album. + 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); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQuery.cs new file mode 100644 index 00000000..ac2975ac --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; + +/// +/// Query for getting an album by its Id. +/// +/// The unique identifier of the media library the album belongs to, taken from the route. +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album to get, taken from the route. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandler.cs new file mode 100644 index 00000000..e0d81c41 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandler.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; + +/// +/// Handler for the query to get an album by its Id. +/// +public class GetAlbumQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetAlbumQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get an album by its Id. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully retrieved , or an error message. + /// + public async Task> HandleAsync(GetAlbumQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + AlbumEntity existingAlbum = getAlbumResult.Value; + + // Resource scoping: the album must belong to the library and the artist named by the route, so that an album can never be read through + // another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return Errors.Music.AlbumNotFound; + + // Admins can see the albums of all libraries; for everyone else, only the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + return existingAlbum.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidator.cs new file mode 100644 index 00000000..c8b19b36 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidator.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; + +/// +/// Validates the needed validation rules for . +/// +public class GetAlbumQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetAlbumQueryValidator() + { + // Validates the identifier of the media library the album belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album to get, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQuery.cs new file mode 100644 index 00000000..8003a14b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; + +/// +/// Query for getting all the tracks of an album. +/// +/// The unique identifier of the media library the album belongs to, taken from the route. +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album whose tracks are retrieved, taken from the route. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumTracksQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandler.cs new file mode 100644 index 00000000..a1da9d43 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandler.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; + +/// +/// Handler for the query to get all the tracks of an album. +/// +public class GetAlbumTracksQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetAlbumTracksQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get all the tracks of an album. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error message. + /// + public async Task>> HandleAsync(GetAlbumTracksQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + AlbumEntity existingAlbum = getAlbumResult.Value; + + // Resource scoping: the album must belong to the library and the artist named by the route, so that the tracks of an album can never be read + // through another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return Errors.Music.AlbumNotFound; + + // Admins can see the tracks of the albums of all libraries; for everyone else, only of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(albumId, cancellationToken).ConfigureAwait(false); + return getTracksResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidator.cs new file mode 100644 index 00000000..014c8c30 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidator.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; + +/// +/// Validates the needed validation rules for . +/// +public class GetAlbumTracksQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksQueryValidator() + { + // Validates the identifier of the media library the album belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album whose tracks are retrieved, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQuery.cs new file mode 100644 index 00000000..aba57b5a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQuery.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; + +/// +/// Query for getting the lightweight read models of all the tracks of an album. +/// +/// The unique identifier of the media library the album belongs to, taken from the route. +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album whose tracks are retrieved, taken from the route. +/// The object containing the requested pagination data. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumTracksLiteQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + PaginationDataDto? PaginationData +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandler.cs new file mode 100644 index 00000000..bc424d69 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandler.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; + +/// +/// Handler for the query to get the lightweight read models of all the tracks of an album. +/// +public class GetAlbumTracksLiteQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetAlbumTracksLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the lightweight read models of all the tracks of an album. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a paginated collection of , or an error message. + /// + public async Task>> HandleAsync(GetAlbumTracksLiteQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + AlbumEntity existingAlbum = getAlbumResult.Value; + + // Resource scoping: the album must belong to the library and the artist named by the route, so that the tracks of an album can never be read + // through another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return Errors.Music.AlbumNotFound; + + // Admins can see the tracks of the albums of all libraries; for everyone else, only of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingAlbum.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getTracksResult = await _unitOfWork.TrackRepository.GetTracksLiteByAlbumIdAsync(albumId, query.PaginationData, cancellationToken).ConfigureAwait(false); + return getTracksResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidator.cs new file mode 100644 index 00000000..6d1e263b --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidator.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; + +/// +/// Validates the needed validation rules for . +/// +public class GetAlbumTracksLiteQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksLiteQueryValidator() + { + // Validates the identifier of the media library the album belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album whose tracks are retrieved, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} 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 new file mode 100644 index 00000000..7fb265bd --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommand.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Contracts.DTO.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// 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 website of the artist, if applicable. +/// The MusicBrainz identifier of the artist, if applicable. +/// The list of media contributors that make up the artist. +/// The list of albums of the artist, each with its own list of tracks. +[DebuggerDisplay("Name: {Name}")] +public record AddArtistCommand( + string? LibraryId, + string? Name, + string? Website, + Guid? MusicBrainzArtistId, + List? Contributors, + List? Albums +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandler.cs new file mode 100644 index 00000000..b5ef8606 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandler.cs @@ -0,0 +1,189 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Handler for the command to add an artist. +/// +public class AddArtistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + /// Injected service for file system path related functionality. + public AddArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + _pathService = pathService; + } + + /// + /// Handles the command to add an artist. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async Task> HandleAsync(AddArtistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + + // Admins can add artists to all libraries; for everyone else, only to the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // An artist can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // An artist's tracks are only readable if they are stored inside one of the content locations of their library, so a client can never + // register an entry that points the reading pipeline at an arbitrary file of the host. + if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command)) + return DomainErrors.Music.TrackPathMustBeWithinLibraryContentLocations; + + // Media contributors are referenced by Id and are never created implicitly by adding an artist, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + + // Convert the command to a domain aggregate to enforce invariants, then persist it in the repository. + Result createArtistResult = command.ToDomainEntity(libraryId); + if (createArtistResult.IsFailure) + return createArtistResult.Errors; + + // Persists the whole aggregate, artist, albums, tracks and their contributors, in a single transaction. + Result insertArtistResult = await _unitOfWork.ArtistRepository.InsertAsync(createArtistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertArtistResult.IsFailure) + return insertArtistResult.Errors; + + // The pre-insert checks handle the common cases; a concurrent request could still persist an artist with the same identity between them + // and the save, in which case the persistence medium reports the unique constraint violation as a conflict. + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Returns the artist as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save. + Result getPersistedArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(createArtistResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedArtistResult.IsFailure) + return getPersistedArtistResult.Errors; + if (getPersistedArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + + return getPersistedArtistResult.Value.ToResponse(); + } + + /// + /// Determines whether every track path referenced by is stored inside one of the content locations of . + /// + /// The media library that owns the artist. + /// The command carrying the referenced tracks. + /// when every referenced track path is within a content location of the library; otherwise, . + private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, AddArtistCommand command) + { + foreach (AddAlbumCommand album in command.Albums!) + foreach (AddTrackCommand track in album.Tracks!) + if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path!, contentLocation.Path))) + return false; + return true; + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(AddArtistCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. CollectContributorIds(command).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return DomainErrors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); + } + + /// + /// Collects the unique identifiers of every media contributor referenced by , be it directly on the artist, + /// or indirectly through one of its albums or the tracks of those albums. + /// + /// The command carrying the referenced media contributors. + /// The collected media contributor identifiers. + private static IEnumerable CollectContributorIds(AddArtistCommand command) + { + foreach (MediaContributorReferenceDto contributor in command.Contributors!) + yield return contributor.ContributorId; + + foreach (AddAlbumCommand album in command.Albums!) + { + foreach (MediaContributorReferenceDto contributor in album.Contributors!) + yield return contributor.ContributorId; + + foreach (AddTrackCommand track in album.Tracks!) + foreach (MediaContributorReferenceDto contributor in track.Contributors!) + yield return contributor.ContributorId; + } + } +} 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 new file mode 100644 index 00000000..4337ed35 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs @@ -0,0 +1,577 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Validates the needed validation rules for . +/// +public class AddArtistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddArtistCommandValidator() + { + // 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); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifying details of the artist. + RuleFor(command => command.Name) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.ArtistNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + + RuleFor(command => command.Website) + .MaximumLength(2048) + .When(command => command.Website is not null) + .WithError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + + RuleFor(command => command.MusicBrainzArtistId) + .Must(musicBrainzArtistId => musicBrainzArtistId != Guid.Empty) + .When(command => command.MusicBrainzArtistId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + // Validates the media contributors that make up the artist. + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates each album created together with the artist, when the request carries albums. + RuleFor(command => command.Albums) + .NotNull() + .WithError(Errors.Music.AlbumsListCannotBeNull); + + RuleForEach(command => command.Albums) + .ChildRules(album => + { + // Validates the metadata of the album: title, lengths, release type and status, and disc and track counts. + album.RuleFor(a => a!.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.AlbumTitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleFor(m => m!.ReleaseType) + .IsInEnum() + .When(m => m!.ReleaseType is not null) + .WithError(Errors.Music.UnknownMusicReleaseType); + + metadata.RuleFor(m => m!.ReleaseStatus) + .IsInEnum() + .When(m => m!.ReleaseStatus is not null) + .WithError(Errors.Music.UnknownMusicReleaseStatus); + + metadata.RuleFor(m => m!.TotalDiscs) + .GreaterThan(0) + .When(m => m!.TotalDiscs.HasValue) + .WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.TotalTracks) + .GreaterThan(0) + .When(m => m!.TotalTracks.HasValue) + .WithError(Errors.Music.TotalTracksMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + 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)); + + metadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the physical characteristics of the album: format and catalog number. + album.RuleFor(a => a!.MediaFormat) + .IsInEnum() + .When(a => a!.MediaFormat is not null) + .WithError(Errors.Music.UnknownMusicMediaFormat); + + album.RuleFor(a => a!.CatalogNumber) + .MaximumLength(50) + .When(a => a!.CatalogNumber is not null) + .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + + album.RuleFor(a => a!.Barcode) + .NotEmpty() + .When(a => a!.Barcode is not null) + .WithError(Errors.Music.BarcodeValueCannotBeEmpty); + + album.RuleFor(a => a!.Barcode) + .Matches(@"^\d{12,13}$") + .When(a => a!.Barcode is not null && a!.Barcode.Length > 0) + .WithError(Errors.Music.InvalidFormatForBarcode); + + // Validates the MusicBrainz identifiers of the album. + album.RuleFor(a => a!.MusicBrainzReleaseId) + .Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty) + .When(a => a!.MusicBrainzReleaseId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + album.RuleFor(a => a!.MusicBrainzReleaseGroupId) + .Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty) + .When(a => a!.MusicBrainzReleaseGroupId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + album.RuleFor(a => a!.MusicBrainzReleaseArtistId) + .Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty) + .When(a => a!.MusicBrainzReleaseArtistId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + // Validates the media contributors that performed on the album. + album.RuleFor(a => a!.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + album.RuleForEach(a => a!.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the album. + album.RuleFor(a => a!.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + album.RuleForEach(a => a!.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 the tracks of the album. + album.RuleFor(a => a!.Tracks) + .NotNull() + .WithError(Errors.Music.TracksListCannotBeNull); + + album.RuleForEach(a => a!.Tracks) + .ChildRules(track => + { + // Validates the file system path of the track. + track.RuleFor(t => t!.Path) + .NotEmpty() + .WithError(Errors.Music.TrackPathCannotBeEmpty) + .MaximumLength(2048) + .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + + // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. + track.RuleFor(t => t!.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(trackMetadata => + { + trackMetadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + trackMetadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + trackMetadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the MusicBrainz identifiers of the track. + track.RuleFor(t => t!.MusicBrainzRecordingId) + .Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty) + .When(t => t!.MusicBrainzRecordingId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + track.RuleFor(t => t!.MusicBrainzTrackId) + .Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty) + .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() + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.TrackNumber) + .GreaterThan(0) + .When(t => t!.TrackNumber.HasValue) + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.DiscNumber) + .GreaterThan(0) + .When(t => t!.DiscNumber.HasValue) + .WithError(Errors.Music.DiscNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.Script) + .MaximumLength(50) + .When(t => t!.Script is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + track.RuleFor(t => t!.Key) + .IsInEnum() + .When(t => t!.Key is not null) + .WithError(Errors.Music.UnknownMusicKey); + + track.RuleFor(t => t!.Bpm) + .GreaterThan(0) + .When(t => t!.Bpm.HasValue) + .WithError(Errors.Music.BpmMustBeGreaterThanZero); + + track.RuleFor(t => t!.Work) + .MaximumLength(255) + .When(t => t!.Work is not null) + .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + + // Validates the moods and the ISRC codes of the track. + track.RuleForEach(t => t!.Moods) + .ChildRules(mood => + mood.RuleFor(m => m.Name) + .NotEmpty() + .WithError(Errors.Metadata.MoodNameCannotBeEmpty)); + + track.RuleForEach(t => t!.Isrcs) + .ChildRules(isrc => + isrc.RuleFor(i => i.Value) + .NotEmpty() + .WithError(Errors.Music.IsrcValueCannotBeEmpty)); + + // Validates the media contributors that performed on the track. + track.RuleFor(t => t!.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + track.RuleForEach(t => t!.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the track. + track.RuleFor(t => t!.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + track.RuleForEach(t => t!.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); + }); + }); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommand.cs new file mode 100644 index 00000000..96966365 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Command for deleting an artist by its Id. +/// +/// The unique identifier of the media library this artist belongs to, taken from the route. +/// The unique identifier of the artist to delete, taken from the route. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record DeleteArtistCommand( + string? LibraryId, + string? ArtistId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs new file mode 100644 index 00000000..5a6d2fbb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Handler for the command to delete an artist by its Id. +/// +public class DeleteArtistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public DeleteArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to delete an artist by its Id. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(DeleteArtistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + + // Only the library of the artist is needed to scope the delete, so the artist row is read without its aggregate graph and without tracking. + Result getArtistResult = await _unitOfWork.ArtistRepository + .GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that an artist can never be deleted through another + // library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can delete the artists of all libraries; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // An artist can only belong to a library that exists, so a client can never delete an artist of a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + Result deleteArtistResult = await _unitOfWork.ArtistRepository.DeleteByIdAsync(artistId, cancellationToken).ConfigureAwait(false); + if (deleteArtistResult.IsFailure) + return deleteArtistResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidator.cs new file mode 100644 index 00000000..44af15c3 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteArtistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteArtistCommandValidator() + { + // Validates the identifier of the media library that owns the artist, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs new file mode 100644 index 00000000..12343cfb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Contracts.DTO.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Command for updating an existing artist. +/// +/// 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 website of the artist, if applicable. +/// The MusicBrainz identifier of the artist, if applicable. +/// The list of media contributors that make up the artist. +/// The list of albums of the artist, each with its own list of tracks. +[DebuggerDisplay("Name: {Name}")] +public record UpdateArtistCommand( + string? LibraryId, + string? ArtistId, + string? Name, + string? Website, + Guid? MusicBrainzArtistId, + List? Contributors, + List? Albums +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandler.cs new file mode 100644 index 00000000..b5574575 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandler.cs @@ -0,0 +1,207 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Handler for the command to update an artist. +/// +public class UpdateArtistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + /// Injected service for file system path related functionality. + public UpdateArtistCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + _pathService = pathService; + } + + /// + /// Handles the command to update an artist. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully updated , or an error message. + /// + public async Task> HandleAsync(UpdateArtistCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + + // An artist is an aggregate root, so the whole aggregate is loaded and the artist is edited within it. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that an artist can never be edited through another + // library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can update the artists of all libraries; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // An artist can only belong to a library that exists, so a client can never update an artist that points to a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // An artist's tracks are only readable if they are stored inside one of the content locations of their library, so a client can never + // edit an entry to point the reading pipeline at an arbitrary file of the host. + if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command)) + return DomainErrors.Music.TrackPathMustBeWithinLibraryContentLocations; + + // Media contributors are referenced by Id and are never created implicitly by editing an artist, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + + // The write path goes through the aggregate root, which is mutated in place, preserving its identity and the identity of its children. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + + Result updateArtistResult = command.ToDomainEntity(artistResult.Value); + if (updateArtistResult.IsFailure) + return updateArtistResult.Errors; + + // Map the updated domain artist onto a fresh repository entity, ready for the repository to replace the stored data. + ArtistEntity updatedArtist = updateArtistResult.Value.ToRepositoryEntity(); + + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(updatedArtist, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Returns the artist as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save. + Result getPersistedArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(existingArtist.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedArtistResult.IsFailure) + return getPersistedArtistResult.Errors; + if (getPersistedArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + + return getPersistedArtistResult.Value.ToResponse(); + } + + /// + /// Determines whether every track path referenced by is stored inside one of the content locations of . + /// + /// The media library that owns the artist. + /// The command carrying the referenced tracks. + /// when every referenced track path is within a content location of the library; otherwise, . + private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, UpdateArtistCommand command) + { + foreach (AddAlbumCommand album in command.Albums!) + foreach (AddTrackCommand track in album.Tracks!) + if (!library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(track.Path!, contentLocation.Path))) + return false; + return true; + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(UpdateArtistCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. CollectContributorIds(command).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return DomainErrors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); + } + + /// + /// Collects the unique identifiers of every media contributor referenced by , be it directly on the artist, + /// or indirectly through one of its albums or the tracks of those albums. + /// + /// The command carrying the referenced media contributors. + /// The collected media contributor identifiers. + private static IEnumerable CollectContributorIds(UpdateArtistCommand command) + { + foreach (MediaContributorReferenceDto contributor in command.Contributors!) + yield return contributor.ContributorId; + + foreach (AddAlbumCommand album in command.Albums!) + { + foreach (MediaContributorReferenceDto contributor in album.Contributors!) + yield return contributor.ContributorId; + + foreach (AddTrackCommand track in album.Tracks!) + foreach (MediaContributorReferenceDto contributor in track.Contributors!) + yield return contributor.ContributorId; + } + } +} 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 new file mode 100644 index 00000000..91c44dd3 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs @@ -0,0 +1,599 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateArtistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCommandValidator() + { + // Validates the identifier of the media library that owns the artist, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifying details of the artist. + RuleFor(command => command.Name) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.ArtistNameCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + + RuleFor(command => command.Website) + .MaximumLength(2048) + .When(command => command.Website is not null) + .WithError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + + RuleFor(command => command.MusicBrainzArtistId) + .Must(musicBrainzArtistId => musicBrainzArtistId != Guid.Empty) + .When(command => command.MusicBrainzArtistId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + // Validates the media contributors that make up the artist. + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates each album updated together with the artist, when the request carries albums. + RuleFor(command => command.Albums) + .NotNull() + .WithError(Errors.Music.AlbumsListCannotBeNull); + + RuleForEach(command => command.Albums) + .ChildRules(album => + { + // Validates the identifier of the album, when the album already exists. + album.RuleFor(a => a!.AlbumId) + .Must(albumId => albumId != Guid.Empty) + .When(a => a!.AlbumId.HasValue) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the metadata of the album: title, lengths, release type and status, and disc and track counts. + album.RuleFor(a => a!.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(metadata => + { + metadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Music.AlbumTitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + metadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + metadata.RuleFor(m => m!.ReleaseType) + .IsInEnum() + .When(m => m!.ReleaseType is not null) + .WithError(Errors.Music.UnknownMusicReleaseType); + + metadata.RuleFor(m => m!.ReleaseStatus) + .IsInEnum() + .When(m => m!.ReleaseStatus is not null) + .WithError(Errors.Music.UnknownMusicReleaseStatus); + + metadata.RuleFor(m => m!.TotalDiscs) + .GreaterThan(0) + .When(m => m!.TotalDiscs.HasValue) + .WithError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.TotalTracks) + .GreaterThan(0) + .When(m => m!.TotalTracks.HasValue) + .WithError(Errors.Music.TotalTracksMustBeGreaterThanZero); + + metadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + 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)); + + metadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + metadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the physical characteristics of the album: format and catalog number. + album.RuleFor(a => a!.MediaFormat) + .IsInEnum() + .When(a => a!.MediaFormat is not null) + .WithError(Errors.Music.UnknownMusicMediaFormat); + + album.RuleFor(a => a!.CatalogNumber) + .MaximumLength(50) + .When(a => a!.CatalogNumber is not null) + .WithError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + + album.RuleFor(a => a!.Barcode) + .NotEmpty() + .When(a => a!.Barcode is not null) + .WithError(Errors.Music.BarcodeValueCannotBeEmpty); + + album.RuleFor(a => a!.Barcode) + .Matches(@"^\d{12,13}$") + .When(a => a!.Barcode is not null && a!.Barcode.Length > 0) + .WithError(Errors.Music.InvalidFormatForBarcode); + + // Validates the MusicBrainz identifiers of the album. + album.RuleFor(a => a!.MusicBrainzReleaseId) + .Must(musicBrainzReleaseId => musicBrainzReleaseId != Guid.Empty) + .When(a => a!.MusicBrainzReleaseId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + album.RuleFor(a => a!.MusicBrainzReleaseGroupId) + .Must(musicBrainzReleaseGroupId => musicBrainzReleaseGroupId != Guid.Empty) + .When(a => a!.MusicBrainzReleaseGroupId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + album.RuleFor(a => a!.MusicBrainzReleaseArtistId) + .Must(musicBrainzReleaseArtistId => musicBrainzReleaseArtistId != Guid.Empty) + .When(a => a!.MusicBrainzReleaseArtistId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + // Validates the media contributors that performed on the album. + album.RuleFor(a => a!.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + album.RuleForEach(a => a!.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the album. + album.RuleFor(a => a!.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + album.RuleForEach(a => a!.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 the tracks of the album. + album.RuleFor(a => a!.Tracks) + .NotNull() + .WithError(Errors.Music.TracksListCannotBeNull); + + album.RuleForEach(a => a!.Tracks) + .ChildRules(track => + { + // Validates the identifier of the track, when the track already exists. + track.RuleFor(t => t!.TrackId) + .Must(trackId => trackId != Guid.Empty) + .When(t => t!.TrackId.HasValue) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + // Validates the file system path of the track. + track.RuleFor(t => t!.Path) + .NotEmpty() + .WithError(Errors.Music.TrackPathCannotBeEmpty) + .MaximumLength(2048) + .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + + // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. + track.RuleFor(t => t!.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(trackMetadata => + { + trackMetadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + trackMetadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + trackMetadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the MusicBrainz identifiers of the track. + track.RuleFor(t => t!.MusicBrainzRecordingId) + .Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty) + .When(t => t!.MusicBrainzRecordingId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + track.RuleFor(t => t!.MusicBrainzTrackId) + .Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty) + .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() + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.TrackNumber) + .GreaterThan(0) + .When(t => t!.TrackNumber.HasValue) + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.DiscNumber) + .GreaterThan(0) + .When(t => t!.DiscNumber.HasValue) + .WithError(Errors.Music.DiscNumberMustBeGreaterThanZero); + + track.RuleFor(t => t!.Script) + .MaximumLength(50) + .When(t => t!.Script is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + track.RuleFor(t => t!.Key) + .IsInEnum() + .When(t => t!.Key is not null) + .WithError(Errors.Music.UnknownMusicKey); + + track.RuleFor(t => t!.Bpm) + .GreaterThan(0) + .When(t => t!.Bpm.HasValue) + .WithError(Errors.Music.BpmMustBeGreaterThanZero); + + track.RuleFor(t => t!.Work) + .MaximumLength(255) + .When(t => t!.Work is not null) + .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + + // Validates the moods and the ISRC codes of the track. + track.RuleForEach(t => t!.Moods) + .ChildRules(mood => + mood.RuleFor(m => m.Name) + .NotEmpty() + .WithError(Errors.Metadata.MoodNameCannotBeEmpty)); + + track.RuleForEach(t => t!.Isrcs) + .ChildRules(isrc => + isrc.RuleFor(i => i.Value) + .NotEmpty() + .WithError(Errors.Music.IsrcValueCannotBeEmpty)); + + // Validates the media contributors that performed on the track. + track.RuleFor(t => t!.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + track.RuleForEach(t => t!.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the track. + track.RuleFor(t => t!.Ratings) + .NotNull() + .WithError(Errors.Metadata.RatingsListCannotBeNull); + + track.RuleForEach(t => t!.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); + }); + }); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQuery.cs new file mode 100644 index 00000000..a9fbb485 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQuery.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Query for getting an artist by its Id. +/// +/// The unique identifier of the media library the artist belongs to, taken from the route. +/// The unique identifier of the artist to get, taken from the route. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistQuery( + string? LibraryId, + string? ArtistId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandler.cs new file mode 100644 index 00000000..6f712640 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandler.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Handler for the query to get an artist by its Id. +/// +public class GetArtistQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetArtistQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get an artist by its Id. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully retrieved , or an error message. + /// + public async Task> HandleAsync(GetArtistQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that an artist can never be read through another + // library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return Errors.Music.ArtistNotFound; + + // Admins can see all artists; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + return existingArtist.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidator.cs new file mode 100644 index 00000000..e87e92e3 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Validates the needed validation rules for . +/// +public class GetArtistQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistQueryValidator() + { + // Validates the identifier of the media library the artist belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist to get, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQuery.cs new file mode 100644 index 00000000..1e09610a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQuery.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Query for getting all the albums of an artist. +/// +/// The unique identifier of the media library the artist belongs to, taken from the route. +/// The unique identifier of the artist whose albums are retrieved, taken from the route. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistAlbumsQuery( + string? LibraryId, + string? ArtistId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandler.cs new file mode 100644 index 00000000..95469502 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandler.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Handler for the query to get all the albums of an artist. +/// +public class GetArtistAlbumsQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetArtistAlbumsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get all the albums of an artist. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error message. + /// + public async Task>> HandleAsync(GetArtistAlbumsQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that the albums of an artist can never be read through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return Errors.Music.ArtistNotFound; + + // Admins can see the albums of the artists of all libraries; for everyone else, only of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(artistId, cancellationToken).ConfigureAwait(false); + return getAlbumsResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidator.cs new file mode 100644 index 00000000..77c4311c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Validates the needed validation rules for . +/// +public class GetArtistAlbumsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsQueryValidator() + { + // Validates the identifier of the media library the artist belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist whose albums are retrieved, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQuery.cs new file mode 100644 index 00000000..280de5bb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Query for getting the lightweight read models of all the albums of an artist. +/// +/// The unique identifier of the media library the artist belongs to, taken from the route. +/// The unique identifier of the artist whose albums are retrieved, taken from the route. +/// The object containing the requested pagination data. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistAlbumsLiteQuery( + string? LibraryId, + string? ArtistId, + PaginationDataDto? PaginationData +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandler.cs new file mode 100644 index 00000000..8637cd0d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandler.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Handler for the query to get the lightweight read models of all the albums of an artist. +/// +public class GetArtistAlbumsLiteQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetArtistAlbumsLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the lightweight read models of all the albums of an artist. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a paginated collection of , or an error message. + /// + public async Task>> HandleAsync(GetArtistAlbumsLiteQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the artist must belong to the library named by the route, so that the albums of an artist can never be read through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return Errors.Music.ArtistNotFound; + + // Admins can see the albums of the artists of all libraries; for everyone else, only of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getAlbumsResult = await _unitOfWork.AlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, query.PaginationData, cancellationToken).ConfigureAwait(false); + return getAlbumsResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidator.cs new file mode 100644 index 00000000..859d3786 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Validates the needed validation rules for . +/// +public class GetArtistAlbumsLiteQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsLiteQueryValidator() + { + // Validates the identifier of the media library the artist belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist whose albums are retrieved, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQuery.cs new file mode 100644 index 00000000..9702dea2 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Query for getting all the artists of a media library. +/// +/// The unique identifier of the media library whose artists are retrieved, taken from the route. +/// The object containing the requested pagination data. +/// The search term used to filter the artists by name. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetArtistsQuery( + string? LibraryId, + PaginationDataDto? PaginationData, + string? SearchTerm +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandler.cs new file mode 100644 index 00000000..2d644d31 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandler.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Handler for the query to get all the artists of a media library. +/// +public class GetArtistsQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetArtistsQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get all the artists of a media library. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a paginated collection of , or an error message. + /// + public async Task>> HandleAsync(GetArtistsQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see the artists of all libraries; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryFilterDto libraryFilter = new() + { + LibraryId = libraryId, + SearchTerm = query.SearchTerm + }; + + Result> getArtistsResult = await _unitOfWork.ArtistRepository + .GetAllAsync(query.PaginationData, filterModel: libraryFilter, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidator.cs new file mode 100644 index 00000000..c285939a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Validates the needed validation rules for . +/// +public class GetArtistsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistsQueryValidator() + { + // Validates the identifier of the media library whose artists are retrieved, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQuery.cs new file mode 100644 index 00000000..53533ad6 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQuery.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.Pagination; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Query for getting the lightweight read models of all the artists of a media library. +/// +/// The unique identifier of the media library whose artists are retrieved, taken from the route. +/// The object containing the requested pagination data. +/// The search term used to filter the artists by name. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetArtistsLiteQuery( + string? LibraryId, + PaginationDataDto? PaginationData, + string? SearchTerm +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandler.cs new file mode 100644 index 00000000..01a281e2 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandler.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Handler for the query to get the lightweight read models of all the artists of a media library. +/// +public class GetArtistsLiteQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetArtistsLiteQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get the lightweight read models of all the artists of a media library. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a paginated collection of , or an error message. + /// + public async Task>> HandleAsync(GetArtistsLiteQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see the artists of all libraries; for everyone else, only the artists of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + LibraryFilterDto filter = new() + { + LibraryId = libraryId, + SearchTerm = query.SearchTerm + }; + + Result> getArtistsResult = await _unitOfWork.ArtistRepository.GetAllLiteAsync( + query.PaginationData, + filterModel: filter, + cancellationToken: cancellationToken).ConfigureAwait(false); + return getArtistsResult.Match(value => Result.From(value.ToResponses()), errors => errors); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidator.cs new file mode 100644 index 00000000..3955889e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidator.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Validates the needed validation rules for . +/// +public class GetArtistsLiteQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistsLiteQueryValidator() + { + // Validates the identifier of the media library whose artists are retrieved, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs new file mode 100644 index 00000000..942f87c4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; + +/// +/// Command for adding a track to an album. +/// +/// The unique identifier of the media library this track belongs to, taken from the route. +/// The unique identifier of the artist this track belongs to, taken from the route. +/// The Id of the album the track belongs to, taken from the route. +/// The file system path of the track. +/// The audio metadata of the track. +/// The number of the track on its disc. +/// The number of the disc the track belongs to, if applicable. +/// 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 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. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record AddTrackCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? Path, + AudioMetadataDto? Metadata, + int? TrackNumber, + int? DiscNumber, + string? Script, + MusicKey? Key, + int? Bpm, + string? Work, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + Guid? MusicBrainzWorkId, + List? Moods, + List? Isrcs, + List? Contributors, + List? Ratings, + Guid? TrackId = null +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandler.cs new file mode 100644 index 00000000..6b1268bb --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandler.cs @@ -0,0 +1,213 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +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.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; + +/// +/// Handler for the command to add a track to an album. +/// +public class AddTrackCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + /// Injected service for file system path related functionality. + public AddTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + _pathService = pathService; + } + + /// + /// Handles the command to add a track to an album. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully created , or an error message. + /// + public async Task> HandleAsync(AddTrackCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + + // A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is added within it. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the track must belong to an artist of the library named by the route, so that a track can never be added through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return Errors.Music.ArtistNotFound; + + // Admins can add tracks to the albums of all libraries; for everyone else, only to the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId); + if (existingAlbum is null) + return Errors.Music.AlbumNotFound; + + // A track can only belong to a library that exists, so a client can never register an entry that points to a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + + // A track is only readable if it is stored inside one of the content locations of its library, so a client can never register an entry + // that points the reading pipeline at an arbitrary file of the host. + if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command)) + return Errors.Music.TrackPathMustBeWithinLibraryContentLocations; + + // Media contributors are referenced by Id and are never created implicitly by adding a track, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + + // The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist, + // which are aggregate roots and are created directly with their own Create method. This difference is intentional. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + + Result createTrackResult = command.ToDomainEntity(); + if (createTrackResult.IsFailure) + return createTrackResult.Errors; + // The album is an entity inside the artist aggregate, so it is referenced by object, not by id; the aggregate member is located here and passed through. + Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId); + if (domainAlbum is null) + return Errors.Music.AlbumNotFound; + Result addTrackResult = artistResult.Value.AddTrackToAlbum(domainAlbum, createTrackResult.Value); + if (addTrackResult.IsFailure) + return addTrackResult.Errors; + + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Reading does not need the aggregate: the track is read directly and mapped to the response. + Result getPersistedTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(createTrackResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedTrackResult.IsFailure) + return getPersistedTrackResult.Errors; + if (getPersistedTrackResult.Value is null) + return Errors.Music.TrackNotFound; + + return getPersistedTrackResult.Value.ToResponse(); + } + + /// + /// Determines whether the track path referenced by is stored inside one of the content locations of . + /// + /// The media library that owns the track. + /// The command carrying the referenced track. + /// when the referenced track path is within a content location of the library; otherwise, . + private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, AddTrackCommand command) + { + return library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path)); + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(AddTrackCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. CollectContributorIds(command).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return Errors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); + } + + /// + /// Collects the unique identifiers of every media contributor referenced by . + /// + /// The command carrying the referenced media contributors. + /// The collected media contributor identifiers. + private static IEnumerable CollectContributorIds(AddTrackCommand command) + { + foreach (MediaContributorReferenceDto contributor in command.Contributors!) + yield return contributor.ContributorId; + } +} 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 new file mode 100644 index 00000000..265649e1 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs @@ -0,0 +1,302 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; + +/// +/// Validates the needed validation rules for . +/// +public class AddTrackCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddTrackCommandValidator() + { + // Validates the identifier of the media library that owns the track, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist that owns the track, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track is added to, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.Path) + .NotEmpty() + .WithError(Errors.Music.TrackPathCannotBeEmpty) + .MaximumLength(2048) + .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + + // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. + RuleFor(command => command.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(trackMetadata => + { + trackMetadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + trackMetadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + trackMetadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the MusicBrainz identifiers of the track. + RuleFor(command => command.MusicBrainzRecordingId) + .Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty) + .When(command => command.MusicBrainzRecordingId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + RuleFor(command => command.MusicBrainzTrackId) + .Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty) + .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() + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + RuleFor(command => command.TrackNumber) + .GreaterThan(0) + .When(command => command.TrackNumber.HasValue) + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + RuleFor(command => command.DiscNumber) + .GreaterThan(0) + .When(command => command.DiscNumber.HasValue) + .WithError(Errors.Music.DiscNumberMustBeGreaterThanZero); + + RuleFor(command => command.Script) + .MaximumLength(50) + .When(command => command.Script is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + RuleFor(command => command.Key) + .IsInEnum() + .When(command => command.Key is not null) + .WithError(Errors.Music.UnknownMusicKey); + + RuleFor(command => command.Bpm) + .GreaterThan(0) + .When(command => command.Bpm.HasValue) + .WithError(Errors.Music.BpmMustBeGreaterThanZero); + + RuleFor(command => command.Work) + .MaximumLength(255) + .When(command => command.Work is not null) + .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + + // Validates the moods and the ISRC codes of the track. + RuleForEach(command => command.Moods) + .ChildRules(mood => + mood.RuleFor(m => m.Name) + .NotEmpty() + .WithError(Errors.Metadata.MoodNameCannotBeEmpty)); + + RuleForEach(command => command.Isrcs) + .ChildRules(isrc => + isrc.RuleFor(i => i.Value) + .NotEmpty() + .WithError(Errors.Music.IsrcValueCannotBeEmpty)); + + // Validates the media contributors that performed on the track. + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the track. + 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); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommand.cs new file mode 100644 index 00000000..bec3aeb5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommand.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; + +/// +/// Command for deleting a track by its Id. +/// +/// The unique identifier of the media library this track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track to delete, taken from the route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record DeleteTrackCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs new file mode 100644 index 00000000..8237a549 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; + +/// +/// Handler for the command to delete a track by its Id. +/// +public class DeleteTrackCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public DeleteTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to delete a track by its Id. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> HandleAsync(DeleteTrackCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + Guid trackId = Guid.Parse(command.TrackId!); + + // A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is removed within it. + Result getArtistResult = await _unitOfWork.ArtistRepository + .GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return DomainErrors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the track must belong to an artist of the library named by the route, so that a track can never be deleted through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return DomainErrors.Music.ArtistNotFound; + + // Admins can delete the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId); + if (existingAlbum is null) + return DomainErrors.Music.AlbumNotFound; + TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == trackId); + if (existingTrack is null) + return DomainErrors.Music.TrackNotFound; + + // A track can only belong to a library that exists, so a client can never delete a track of a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // The write path goes through the aggregate root: a track is a child entity of the artist aggregate, unlike Book and Artist, + // which are aggregate roots and are deleted directly through their own repositories. This difference is intentional. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + // The album and the track are entities inside the artist aggregate, so they are referenced by object, not by id; the aggregate members are located here and passed through. + Album? domainAlbum = artistResult.Value.Albums.FirstOrDefault(album => album.Id.Value == albumId); + if (domainAlbum is null) + return DomainErrors.Music.AlbumNotFound; + Track? domainTrack = domainAlbum.Tracks.FirstOrDefault(track => track.Id.Value == trackId); + if (domainTrack is null) + return DomainErrors.Music.TrackNotFound; + Result removeTrackResult = artistResult.Value.RemoveTrackFromAlbum(domainAlbum, domainTrack); + if (removeTrackResult.IsFailure) + return removeTrackResult.Errors; + + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(artistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidator.cs new file mode 100644 index 00000000..abfc3236 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; + +/// +/// Validates the needed validation rules for . +/// +public class DeleteTrackCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteTrackCommandValidator() + { + // Validates the identifier of the media library that owns the track, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track to delete, taken from the route. + RuleFor(command => command.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(command => command.TrackId is not null && command.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs new file mode 100644 index 00000000..2f67a920 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; + +/// +/// Command for updating a track. +/// +/// The unique identifier of the media library this track belongs to, taken from the route. +/// The unique identifier of the artist this track belongs to, taken from the route. +/// The unique identifier of the album this track belongs to, taken from the route. +/// The unique identifier of the track, taken from the route. +/// The file system path of the track. +/// The audio metadata of the track. +/// The number of the track on its disc. +/// The number of the disc the track belongs to, if applicable. +/// 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 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. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateTrackCommand( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId, + string? Path, + AudioMetadataDto? Metadata, + int? TrackNumber, + int? DiscNumber, + string? Script, + MusicKey? Key, + int? Bpm, + string? Work, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + Guid? MusicBrainzWorkId, + List? Moods, + List? Isrcs, + List? Contributors, + List? Ratings +) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs new file mode 100644 index 00000000..bced0f6d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs @@ -0,0 +1,211 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +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.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +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.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; + +/// +/// Handler for the command to update a track. +/// +public class UpdateTrackCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + private readonly IPathService _pathService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + /// Injected service for file system path related functionality. + public UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + _pathService = pathService; + } + + /// + /// Handles the command to update a track. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully updated , or an error message. + /// + public async Task> HandleAsync(UpdateTrackCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + Guid trackId = Guid.Parse(command.TrackId!); + + // A track is a child of the artist aggregate, so the whole aggregate is loaded and the track is edited within it. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + ArtistEntity existingArtist = getArtistResult.Value; + + // Resource scoping: the track must belong to an artist of the library named by the route, so that a track can never be edited through + // another library's route; the mismatch is reported as not found, without disclosing that the artist exists in another library. + if (existingArtist.LibraryId != libraryId) + return Errors.Music.ArtistNotFound; + + // Admins can update the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingArtist.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + AlbumEntity? existingAlbum = existingArtist.Albums.FirstOrDefault(album => album.Id == albumId); + if (existingAlbum is null) + return Errors.Music.AlbumNotFound; + TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == trackId); + if (existingTrack is null) + return Errors.Music.TrackNotFound; + + // A track can only belong to a library that exists, so a client can never update a track of a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + + // A track is only readable if it is stored inside one of the content locations of its library, so a client can never edit an entry + // that points the reading pipeline at an arbitrary file of the host. + if (!AreTrackPathsWithinLibraryContentLocations(getLibraryResult.Value, command)) + return Errors.Music.TrackPathMustBeWithinLibraryContentLocations; + + // Media contributors are referenced by Id and are never created implicitly by editing a track, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + + // The write path goes through the aggregate root: a track is a child entity of the artist aggregate, so it is mutated through its owning + // artist. Book is itself an aggregate root, so its update flow reconstitutes it directly with its own Create method instead. + Result artistResult = existingArtist.ToDomainEntity(); + if (artistResult.IsFailure) + return artistResult.Errors; + + Result updatedArtistResult = command.ToDomainEntity(artistResult.Value); + if (updatedArtistResult.IsFailure) + return updatedArtistResult.Errors; + + Result updateResult = await _unitOfWork.ArtistRepository.UpdateAsync(updatedArtistResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Reading does not need the aggregate: the track is read directly and mapped to the response. + Result getPersistedTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedTrackResult.IsFailure) + return getPersistedTrackResult.Errors; + if (getPersistedTrackResult.Value is null) + return Errors.Music.TrackNotFound; + + return getPersistedTrackResult.Value.ToResponse(); + } + + /// + /// Determines whether the track path referenced by is stored inside one of the content locations of . + /// + /// The media library that owns the track. + /// The command carrying the referenced track. + /// when the referenced track path is within a content location of the library; otherwise, . + private bool AreTrackPathsWithinLibraryContentLocations(LibraryEntity library, UpdateTrackCommand command) + { + return library.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path)); + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(UpdateTrackCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. CollectContributorIds(command).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return Errors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); + } + + /// + /// Collects the unique identifiers of every media contributor referenced by . + /// + /// The command carrying the referenced media contributors. + /// The collected media contributor identifiers. + private static IEnumerable CollectContributorIds(UpdateTrackCommand command) + { + foreach (MediaContributorReferenceDto contributor in command.Contributors!) + yield return contributor.ContributorId; + } +} 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 new file mode 100644 index 00000000..0ebf84e5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs @@ -0,0 +1,312 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; + +/// +/// Validates the needed validation rules for . +/// +public class UpdateTrackCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateTrackCommandValidator() + { + // Validates the identifier of the media library that owns the track, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist that owns the track, taken from the route. + RuleFor(command => command.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(command => command.ArtistId is not null && command.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album that owns the track, taken from the route. + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(command => command.AlbumId is not null && command.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track, taken from the route. + RuleFor(command => command.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(command => command.TrackId is not null && command.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.Path) + .NotEmpty() + .WithError(Errors.Music.TrackPathCannotBeEmpty) + .MaximumLength(2048) + .WithError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + + // Validates the audio metadata of the track: title, lengths, release information, languages, genres and tags. + RuleFor(command => command.Metadata) + .NotNull() + .WithError(Errors.Metadata.MetadataCannotBeNull) + .ChildRules(trackMetadata => + { + trackMetadata.RuleFor(m => m!.Title) + .NotNull() + .NotEmpty() + .WithError(Errors.Metadata.TitleCannotBeEmpty) + .MaximumLength(255) + .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.OriginalTitle) + .MaximumLength(255) + .When(m => m!.OriginalTitle is not null) + .WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + + trackMetadata.RuleFor(m => m!.Description) + .MaximumLength(2000) + .When(m => m!.Description is not null) + .WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + + trackMetadata.RuleFor(m => m!.ReleaseInfo) + .NotNull() + .WithError(Errors.Metadata.ReleaseInfoCannotBeNull) + .ChildRules(releaseInfo => + { + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .InclusiveBetween(1, 9999) + .When(r => r!.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + + releaseInfo.RuleFor(r => r!.ReleaseVersion) + .MaximumLength(50) + .When(r => r!.ReleaseVersion is not null) + .WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + + releaseInfo.RuleFor(r => r!.OriginalReleaseYear) + .Must((releaseInfoInstance, originalReleaseYear) => + !releaseInfoInstance!.OriginalReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year) + .When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.ReReleaseYear.HasValue || + reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year) + .When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + + releaseInfo.RuleFor(r => r!.ReReleaseYear) + .Must((releaseInfoInstance, reReleaseYear) => + !releaseInfoInstance!.ReReleaseYear.HasValue || + !releaseInfoInstance.OriginalReleaseYear.HasValue || + reReleaseYear >= releaseInfoInstance.OriginalReleaseYear) + .When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue) + .WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + + releaseInfo.RuleFor(r => r!.ReReleaseDate) + .Must((releaseInfoInstance, reReleaseDate) => + !releaseInfoInstance!.ReReleaseDate.HasValue || + !releaseInfoInstance.OriginalReleaseDate.HasValue || + reReleaseDate >= releaseInfoInstance.OriginalReleaseDate) + .When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue) + .WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + }); + + trackMetadata.RuleFor(m => m!.Genres) + .NotNull() + .WithError(Errors.Metadata.GenresListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Genres) + .ChildRules(genre => + genre.RuleFor(g => g.Name) + .NotEmpty() + .WithError(Errors.Metadata.GenreNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Tags) + .NotNull() + .WithError(Errors.Metadata.TagsListCannotBeNull); + + trackMetadata.RuleForEach(m => m!.Tags) + .ChildRules(tag => + tag.RuleFor(t => t.Name) + .NotEmpty() + .WithError(Errors.Metadata.TagNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong)); + + trackMetadata.RuleFor(m => m!.Language!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.Language!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.Language is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) + .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.LanguageName) + .NotEmpty() + .WithError(Errors.Metadata.LanguageNameCannotBeEmpty) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + + trackMetadata.RuleFor(m => m!.OriginalLanguage!.NativeName) + .MaximumLength(50) + .WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong) + .When(m => m!.OriginalLanguage is not null); + }); + + // Validates the MusicBrainz identifiers of the track. + RuleFor(command => command.MusicBrainzRecordingId) + .Must(musicBrainzRecordingId => musicBrainzRecordingId != Guid.Empty) + .When(command => command.MusicBrainzRecordingId.HasValue) + .WithError(Errors.Music.MusicBrainzIdInvalidFormat); + + RuleFor(command => command.MusicBrainzTrackId) + .Must(musicBrainzTrackId => musicBrainzTrackId != Guid.Empty) + .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() + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + RuleFor(command => command.TrackNumber) + .GreaterThan(0) + .When(command => command.TrackNumber.HasValue) + .WithError(Errors.Music.TrackNumberMustBeGreaterThanZero); + + RuleFor(command => command.DiscNumber) + .GreaterThan(0) + .When(command => command.DiscNumber.HasValue) + .WithError(Errors.Music.DiscNumberMustBeGreaterThanZero); + + RuleFor(command => command.Script) + .MaximumLength(50) + .When(command => command.Script is not null) + .WithError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + + RuleFor(command => command.Key) + .IsInEnum() + .When(command => command.Key is not null) + .WithError(Errors.Music.UnknownMusicKey); + + RuleFor(command => command.Bpm) + .GreaterThan(0) + .When(command => command.Bpm.HasValue) + .WithError(Errors.Music.BpmMustBeGreaterThanZero); + + RuleFor(command => command.Work) + .MaximumLength(255) + .When(command => command.Work is not null) + .WithError(Errors.Music.WorkMustBeMaximum255CharactersLong); + + // Validates the moods and the ISRC codes of the track. + RuleForEach(command => command.Moods) + .ChildRules(mood => + mood.RuleFor(m => m.Name) + .NotEmpty() + .WithError(Errors.Metadata.MoodNameCannotBeEmpty)); + + RuleForEach(command => command.Isrcs) + .ChildRules(isrc => + isrc.RuleFor(i => i.Value) + .NotEmpty() + .WithError(Errors.Music.IsrcValueCannotBeEmpty)); + + // Validates the media contributors that performed on the track. + RuleFor(command => command.Contributors) + .NotNull() + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); + + RuleForEach(command => command.Contributors) + .ChildRules(contributor => + { + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + + contributor.RuleFor(c => c.Role) + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); + }); + + // Validates the ratings of the track. + 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); + }); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQuery.cs new file mode 100644 index 00000000..ef8bb9df --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQuery.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; + +/// +/// Query for getting a track by its Id. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track to get, taken from the route. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetTrackQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandler.cs new file mode 100644 index 00000000..f74fad1f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandler.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; + +/// +/// Handler for the query to get a track by its Id. +/// +public class GetTrackQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected validator for application validation rules. + public GetTrackQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the query to get a track by its Id. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a successfully retrieved , or an error message. + /// + public async Task> HandleAsync(GetTrackQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers are non-empty Guids before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + + // The album is loaded first, so that the artist and the library named by the route are enforced before the track itself is read. + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + AlbumEntity existingAlbum = getAlbumResult.Value; + + // Resource scoping: the album must belong to the artist and the library named by the route, so that a track can never be read through + // another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return Errors.Music.AlbumNotFound; + + Result getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return Errors.Music.TrackNotFound; + TrackEntity existingTrack = getTrackResult.Value; + + // Resource scoping: the track must belong to the album and the library named by the route, so that a track of another album can never + // be read through this album's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere. + if (existingTrack.AlbumId != albumId || existingTrack.LibraryId != libraryId) + return Errors.Music.TrackNotFound; + + // Admins can see the tracks of all libraries; for everyone else, only the tracks of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingTrack.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + return existingTrack.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidator.cs new file mode 100644 index 00000000..01944816 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidator.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track to get, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} 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 983bdf9e..44e6272e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -83,18 +83,18 @@ public class AddLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins or users with the permission to manage media libraries can create them + // Only admins or users with the permission to manage media libraries can create them. if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false) && !await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)) return ApplicationErrors.Authorization.NotAuthorized; - // make sure the file is an actual supported image + // Make sure the file is an actual supported image. if (command.CoverImage is not null) { Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); @@ -108,13 +108,13 @@ public class AddLibraryCommandHandler : ICommandHandler createLibraryResult = Library.Create( UserId.Create(userId), command.Title!, Enum.Parse(command.LibraryType!), command.ContentLocations!, - command.CoverImage, + Optional.FromNullable(command.CoverImage), command.IsEnabled, command.IsLocked, command.CanDownloadMetadataFromWeb, @@ -126,10 +126,10 @@ public class AddLibraryCommandHandler : ICommandHandler insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; @@ -137,19 +137,22 @@ public class AddLibraryCommandHandler : ICommandHandler(command.LibraryType!), cancellationToken).ConfigureAwait(false); if (ensureProviderConfigurationsResult.IsFailure) return ensureProviderConfigurationsResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // retrieve the newly saved media library from the persistence medium and return it - Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Retrieve the newly saved media library from the persistence medium and return it. + Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; - // mark the media library as saved + // Mark the media library as saved. createLibraryResult.Value.Save(); - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs index 42ceb8d3..c32ba282 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandler.cs @@ -58,53 +58,55 @@ public class CancelLibrariesScanCommandHandler : ICommandHandlerAn representing either a successful operation, or an error. public async Task> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the running library scans of the current user from the repository + // Get the running library scans of the current user from the repository. Result> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false); if (getRunningLibraryScansResult.IsFailure) return getRunningLibraryScansResult.Errors; - // filter the library scans to process + // Filter the library scans to process. List authorizedLibraryScans = []; - // admins can see all library scans + // Admins can see all library scans. if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value); - else // for regular users, only take the library scans that belong to them + else // For regular users, only take the library scans that belong to them. authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId)); - // convert persistence library scans to domain entities + // Convert persistence library scans to domain entities. IEnumerable> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities(); List domainEvents = []; - // for each library scan, perform the cancellation + // For each library scan, perform the cancellation. foreach (Result libraryScanDomainResult in libraryScansDomainResult) { if (libraryScanDomainResult.IsFailure) return libraryScanDomainResult.Errors; - // cancel the media library scan + // Cancel the media library scan. Result cancelScanResult = libraryScanDomainResult.Value.CancelScan(); if (cancelScanResult.IsFailure) return cancelScanResult.Errors; - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; - // collect all the domain events created during this library scan start + // Collect all the domain events created during this library scan start. domainEvents.AddRange(libraryScanDomainResult.Value.GetDomainEvents()); } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in domainEvents) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs index f4d0e4bb..57ce568e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandler.cs @@ -67,43 +67,45 @@ public class CancelLibraryScanCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library scan from the repository - Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false); + // Get the library scan from the repository. + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) return getLibraryScansResult.Errors; if (getLibraryScansResult.Value is null) return DomainErrors.LibraryScanning.LibraryScanNotFound; - // admins can cancel any library scan; for everyone else, only the ones of the libraries they own + // Admins can cancel any library scan; for everyone else, only the ones of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(getLibraryScansResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) return libraryScanDomainResult.Errors; - // cancel the media library scan + // Cancel the media library scan. Result cancelScanResult = libraryScanDomainResult.Value.CancelScan(); if (cancelScanResult.IsFailure) return cancelScanResult.Errors; - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) return updateLibraryScanResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in libraryScanDomainResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index 968f92d4..ae7b4e06 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -72,48 +72,51 @@ public class DeleteLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library with the specified id from the repository - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + // Get the library with the specified id from the repository. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can delete any library; for everyone else, only the libraries they own + // Admins can delete any library; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // create a domain library object + // Create a domain library object. Result createLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (createLibraryResult.IsFailure) return createLibraryResult.Errors; - // delete the domain aggregate + // Delete the domain aggregate. Result deleteDomainLibraryResult = createLibraryResult.Value.Delete(); if (deleteDomainLibraryResult.IsFailure) return deleteDomainLibraryResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); - // remove the provider configurations of the library, so that they are not orphaned, and delete the library + // Remove the provider configurations of the library, so that they are not orphaned, and delete the library. Result removeProviderConfigurationsResult = await _providerConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, cancellationToken).ConfigureAwait(false); if (removeProviderConfigurationsResult.IsFailure) return removeProviderConfigurationsResult.Errors; Result deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (deletePersistenceLibraryResult.IsFailure) return deletePersistenceLibraryResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return deletePersistenceLibraryResult; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return Result.Deleted; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs index ded8c73b..139ab583 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandler.cs @@ -61,46 +61,46 @@ public class ScanLibrariesCommandHandler : ICommandHandlerAn representing either a successful operation, or an error. public async Task>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get all media libraries that are enabled and unlocked from the persistence medium + // Get all media libraries that are enabled and unlocked from the persistence medium. Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; - // convert persistence libraries to domain entities + // Convert persistence libraries to domain entities. IEnumerable> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities(); - // if the current user is not an admin, they can only scan the libraries that belong to them + // If the current user is not an admin, they can only scan the libraries that belong to them. if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId); List responses = []; List domainEvents = []; - // for each library, start the scan + // For each library, start the scan. foreach (Result domainLibraryResult in domainEntitiesResult) { if (domainLibraryResult.IsFailure) return domainLibraryResult.Errors; - // get the past month's scans for this library + // Get the past month's scans for this library. Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(domainLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; - // convert the repository scans history to domain objects + // Convert the repository scans history to domain objects. IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) if (pastLibraryScanDomainResult.IsFailure) return pastLibraryScanDomainResult.Errors; - // start the media library scan + // Start the media library scan. Result libraryScanResult = LibraryScan.Create( LibraryId.Create(domainLibraryResult.Value.Id.Value), UserId.Create(userId), @@ -110,25 +110,27 @@ public class ScanLibrariesCommandHandler : ICommandHandler startScanResult = libraryScanResult.Value.QueueScan(); - // when the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned. - // instead, just don't start the scan on such a library, and start it on the others that can be started + // When the user demands a "scan all libraries" action, it would be annoying to receive an error if a library is already being scanned. + // Instead, just don't start the scan on such a library, and start it on the others that can be started. if (startScanResult.IsFailure) continue; - // add the library scan to the persistence medium + // Add the library scan to the persistence medium. Result insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; - // collect all the domain events created during this library scan start + // Collect all the domain events created during this library scan start. domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); responses.Add(new MediaLibraryScanResponse(libraryScanResult.Value.Id.Value, domainLibraryResult.Value.Id.Value)); } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in domainEvents) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs index 1f0763d1..d3ad0b32 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandler.cs @@ -73,50 +73,50 @@ public class ScanLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the media library from the persistence medium - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + // Get the media library from the persistence medium. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can scan any library; for everyone else, only the libraries they own + // Admins can scan any library; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // check if the library is enabled and unlocked, before scanning it + // Check if the library is enabled and unlocked, before scanning it. if (!getLibraryResult.Value.IsEnabled) return DomainErrors.Library.CannotScanDisabledLibrary; if (getLibraryResult.Value.IsLocked) return DomainErrors.Library.CannotScanLockedLibrary; - // convert the persistence library to a domain entity + // Convert the persistence library to a domain entity. Result domainLibraryResult = getLibraryResult.Value.ToDomainEntity(); if (domainLibraryResult.IsFailure) return domainLibraryResult.Errors; - // get the past month's scans for this library + // Get the past month's scans for this library. Result> pastLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (pastLibraryScansResult.IsFailure) return pastLibraryScansResult.Errors; - // convert the repository scans history to domain objects + // Convert the repository scans history to domain objects. IEnumerable> pastLibraryScansDomainResult = pastLibraryScansResult.Value.ToDomainEntities(); foreach (Result pastLibraryScanDomainResult in pastLibraryScansDomainResult) if (pastLibraryScanDomainResult.IsFailure) return pastLibraryScanDomainResult.Errors; - // queue the media library scan + // Queue the media library scan. Result libraryScanResult = LibraryScan.Create( LibraryId.Create(command.Id), UserId.Create(userId), @@ -129,14 +129,16 @@ public class ScanLibraryCommandHandler : ICommandHandler insertLibraryScanResult = await _unitOfWork.LibraryScanRepository.InsertAsync(libraryScanResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertLibraryScanResult.IsFailure) return insertLibraryScanResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in libraryScanResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); 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 52de01c6..42fe46cb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -87,21 +87,21 @@ public class UpdateLibraryCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get a library repository and retrieve the library to update - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + // Get a library repository and retrieve the library to update. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is - // relative to the application base directory and is already validated, so it must not block saving unrelated changes + // Make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is + // relative to the application base directory and is already validated, so it must not block saving unrelated changes. if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage) { Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); @@ -115,14 +115,14 @@ public class UpdateLibraryCommandHandler : ICommandHandler( userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false); if (!hasManagePermission && !canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // create a domain library object + // Create a domain library object. LibraryType newLibraryType = Enum.Parse(command.LibraryType!); Result createLibraryResult = Library.Create( LibraryId.Create(command.Id), @@ -130,7 +130,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler.FromNullable(command.CoverImage), command.IsEnabled, command.IsLocked, command.CanDownloadMetadataFromWeb, @@ -140,11 +140,11 @@ public class UpdateLibraryCommandHandler : ICommandHandler updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; @@ -154,19 +154,21 @@ public class UpdateLibraryCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - // retrieve the updated media library from the persistence medium and return it - Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); + // Retrieve the updated media library from the persistence medium and return it. + Result getCreatedLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsFailure) return getCreatedLibraryResult.Errors; if (getCreatedLibraryResult.Value is null) return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary; - // mark the media library as saved + // Mark the media library as saved. createLibraryResult.Value.Save(); - // queue any domain events + // Queue any domain events. foreach (IDomainEvent domainEvent in createLibraryResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(domainEvent); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs index 551cd269..7c68e86b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandler.cs @@ -48,7 +48,7 @@ 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); @@ -56,8 +56,8 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + // 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) throw new EventualConsistencyException(getLibraryResult.FirstError, getLibraryResult.Errors); LibraryEntity library = getLibraryResult.Value; @@ -71,11 +71,13 @@ public class LibraryMediaItemDeletedDomainEventHandler : IDomainEventHandler deleteBookResult = await _unitOfWork.BookRepository.DeleteAsync(book.Id, cancellationToken).ConfigureAwait(false); + // 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); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index 9772737d..59f79bdc 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -58,21 +58,23 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken) { - if (domainEvent.Library.CoverImage is not null) + if (domainEvent.Library.CoverImage.HasValue) { - // attempt to copy the image from the original location provided by the user to the internal location for media library files - Result saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage, cancellationToken).ConfigureAwait(false); + // Attempt to copy the image from the original location provided by the user to the internal location for media library files. + Result saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage.Value, cancellationToken).ConfigureAwait(false); if (saveCoverImageResult.IsFailure) throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors); domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value); - // update the media library with the new cover location + // Update the media library with the new cover location. Result updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } - else // no cover image is provided, delete any cover image that might exist in the internal location for media library files + else // No cover image is provided, delete any cover image that might exist in the internal location for media library files. { Result libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); if (libraryPathResult.IsFailure) @@ -90,17 +92,17 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler private Result GetLibraryPath(Guid libraryId) { - // root directory for media + // Root directory for media. Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); if (rootPathResult.IsFailure) return rootPathResult.Errors; - // libraries directory + // Libraries directory. Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); if (librariesPathResult.IsFailure) return librariesPathResult.Errors; - // this new particular library' directory + // This new particular library's directory. Result libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); if (libraryPathResult.IsFailure) return libraryPathResult.Errors; @@ -142,8 +144,8 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler internalImagePathIdResult = ResolveInternalMediaPathId(imagePath); @@ -157,19 +159,19 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); if (imageCheckResult.IsFailure) return imageCheckResult.Errors; if (imageCheckResult.Value == ImageType.None) return Errors.Library.CoverFileMustBeAnImage; - // the provided cover image path exists and is a valid image, store it in the media directory - Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media + // The provided cover image path exists and is a valid image, store it in the media directory. + Result rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // Root directory for media. if (rootPathResult.IsFailure) return rootPathResult.Errors; - Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory + Result librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // Libraries directory. if (librariesPathResult.IsFailure) return librariesPathResult.Errors; @@ -181,7 +183,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler libraryPathResult = GetLibraryPath(libraryId); if (libraryPathResult.IsFailure) return libraryPathResult.Errors; @@ -190,7 +192,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value); if (directoryExistsResult.IsFailure) return directoryExistsResult.Errors; @@ -203,24 +205,24 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); if (deleteExistingCoverImageResult.IsFailure) return deleteExistingCoverImageResult.Errors; } - // copy the new cover file from the location provided by the user + // Copy the new cover file from the location provided by the user. Result copyFileResult = _environmentContext.FileProviderService.CopyFile(fileSystemPathIdResult.Value, newLibraryPathIdResult.Value, true); if (copyFileResult.IsFailure) return copyFileResult.Errors; - // rename the new cover file to the standard naming + // Rename the new cover file to the standard naming. Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}"); if (renameFileResult.IsFailure) return renameFileResult.Errors; - // get the internal relative path for the copied file + // 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}"; @@ -239,7 +241,7 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler> getExistingLibraryFilesResult = _environmentContext.FileProviderService.GetFilePaths(newLibraryPathIdResult.Value, true); if (getExistingLibraryFilesResult.IsFailure) return getExistingLibraryFilesResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index 64e841e5..c87a10b2 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -56,25 +56,24 @@ public class LibraryScanCancelledDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanCancelledDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan from the repository - Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + // Get the library scan from the repository. + Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // cancel the media library scan + // Cancel the media library scan. Result cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value); if (cancelScanResult.IsFailure) throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors); - // release the scan processing resources - + // Release the scan processing resources. MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId)); _mediaLibrariesScanCancellationTracker.RemoveScan(compositeId); _mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index 483bbccf..f56f5bcd 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -54,41 +54,43 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan from the repository + // Get the library scan from the repository. Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( - domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); + domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScanResult.IsFailure) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); if (getLibraryScanResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // mark the media library scan as failed + // Mark the media library scan as failed. Result failScanResult = libraryScanDomainResult.Value.FailScan(); - // we're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event, - // trying to set as failed a scan that has already been marked as failed by a concurrent job + // We're going to ignore errors in this point, because scan jobs run in parallel, and two concurrent jobs of the same scan might trigger this domain event, + // trying to set as failed a scan that has already been marked as failed by a concurrent job. if (!failScanResult.IsFailure) { - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } - // release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job + // Release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job. _mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId); _mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId); Result clearStagingResult = await _unitOfWork.LibraryScanStagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); if (clearStagingResult.IsFailure) throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); - // notify SignalR clients that the library scan failed + // Notify SignalR clients that the library scan failed. await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs index c541f390..034c50ba 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandler.cs @@ -54,36 +54,38 @@ public class LibraryScanFinishedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanFinishedDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan from the repository + // Get the library scan from the repository. Result getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( - domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); + domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScansResult.IsFailure) throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); if (getLibraryScansResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository scan to a domain object + // Convert the repository scan to a domain object. Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // mark the media library scan as finished + // Mark the media library scan as finished. Result finishScanResult = libraryScanDomainResult.Value.FinishScan(); if (finishScanResult.IsFailure) throw new EventualConsistencyException(finishScanResult.FirstError, finishScanResult.Errors); - // update the library scan in the repository + // Update the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(libraryScanDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); - // mark the scan progress as finished + // Mark the scan progress as finished. _mediaLibrariesScanProgressTracker.UpdateScanProgress(libraryScanDomainResult.Value.LibraryId, domainEvent.MediaLibraryScanCompositeId); - // notify SignalR clients that the library scan finished + // Notify SignalR clients that the library scan finished. await _debouncedLibraryScanProgressNotifier.SendLibraryScanFinishedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false); - // only when everything is done, this needs to be called in order to dispose cancellation token sources, etc + // Only when everything is done, this needs to be called in order to dispose cancellation token sources, etc. _mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index d77ae07f..6895eaee 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -46,25 +46,25 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanQueuedDomainEvent domainEvent, CancellationToken cancellationToken) { - // get the library scan that was queued, from the repository - Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + // Get the library scan that was queued, from the repository. + Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryScanResult.IsFailure) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); if (getLibraryScanResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); - // convert the repository entity to a domain entity + // Convert the repository entity to a domain entity. Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); - // start the media library scan + // Start the media library scan. Result startScanResult = await _mediaLibraryScanningService.StartScanAsync( libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false); if (startScanResult.IsFailure) throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); - // queue any domain events + // Queue any domain events. foreach (IDomainEvent queuedDomainEvent in libraryScanDomainResult.Value.GetDomainEvents()) _domainEventsQueue.Enqueue(queuedDomainEvent); } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs index ac2140c8..3f17b5d9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandler.cs @@ -35,11 +35,13 @@ public class LibraryScanStartedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(LibraryScanStartedDomainEvent domainEvent, CancellationToken cancellationToken) { - // update the status of the library scan in the repository + // Update the status of the library scan in the repository. Result updateLibraryScanResult = await _unitOfWork.LibraryScanRepository.UpdateAsync(domainEvent.LibraryScan.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateLibraryScanResult.IsFailure) throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs index 620aa06b..56b7ac87 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandler.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.CQRS; 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.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -53,24 +55,24 @@ public class GetLibrariesQueryHandler : IQueryHandler public async Task> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the libraries from the repository - Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Get the libraries from the repository. + Result> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) return getLibrariesResult.Errors; - // admins can see all libraries + // Admins can see all libraries. if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false)) - return Result.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray()); + return Result.From(getLibrariesResult.Value.Data.Select(library => library.ToResponse()).ToArray()); else { - // for regular users, only take the libraries that belong to them - LibraryResponse[] userLibraries = [.. getLibrariesResult.Value + // For regular users, only take the libraries that belong to them. + LibraryResponse[] userLibraries = [.. getLibrariesResult.Value.Data .Where(library => library.UserId == userId) .Select(library => library.ToResponse())]; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs index d9a35d7a..d1f0ec67 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandler.cs @@ -64,20 +64,20 @@ public class GetLibraryQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library with the specified id from the repository - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); + // Get the library with the specified id from the repository. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can see all libraries; for everyone else, only the libraries they own + // Admins can see all libraries; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.Id), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs index 0ea12e65..3de2d660 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandler.cs @@ -71,20 +71,20 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // get the library with the specified id from the repository - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + // Get the library with the specified id from the repository. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; else if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; - // admins can view the progress of any library scan; for everyone else, only the ones of the libraries they own + // Admins can view the progress of any library scan; for everyone else, only the ones of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs index d83688e4..365d765c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; @@ -14,7 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Command for adding a book. /// -/// The Id of the media library this book belongs to. +/// The unique identifier of the media library this book belongs to, taken from the route. /// The file system path of the book. /// Written content metadata of the book. /// The format of the book (e.g., Hardcover, Paperback), if applicable. @@ -31,12 +31,12 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// The Barnes & Noble ID of the book, if applicable. /// The Apple Books ID of the book, if applicable. /// The list of ISBN (International Standard Book Number) of the book. -/// The list of media contributors (actors, directors, etc) starring in this book. +/// The list of media contributors that contributed to this book. /// The list of ratings for this book. [DebuggerDisplay("Title: {Metadata.Title}")] public record AddBookCommand( - Guid LibraryId, - string Path, + string? LibraryId, + string? Path, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, @@ -52,6 +52,6 @@ public record AddBookCommand( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs index a1946a34..cc545bff 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandler.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; 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.UoW; using Lumina.Application.Common.Infrastructure.Authentication; @@ -8,24 +9,17 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; @@ -39,6 +33,7 @@ public class AddBookCommandHandler : ICommandHandler _validator; + private readonly IPathService _pathService; /// /// Initializes a new instance of the class. @@ -47,12 +42,14 @@ public class AddBookCommandHandler : ICommandHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected validator for application validation rules. - public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + /// Injected service for file system path related functionality. + public AddBookCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator, IPathService pathService) { _unitOfWork = unitOfWork; _authorizationService = authorizationService; _currentUserService = currentUserService; _validator = validator; + _pathService = pathService; } /// @@ -75,163 +72,75 @@ public class AddBookCommandHandler : ICommandHandler( - userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // TODO: update Api.Book.md documentation when the functionality is fully implemented. - BookSeries? bookSeries = null; - if (command.Series != null) - { - // TODO: add logic to search the book series repository for existing book series, based on the provided title. - // TODO: uncomment integration and unit tests about series. - } - List> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create( - rating.Value ?? default, - rating.MaxValue ?? default, - Optional.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null), - Optional.FromNullable(rating.VoteCount))); - // Check if any of the results contain errors. - List errors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsFailure).SelectMany(ratingResult => ratingResult.Errors)]; - if (errors.Count != 0) // if there are errors, return them - return errors; + // A book is only readable if it is stored inside one of the content locations of its library, so a client can never register an entry that points the reading pipeline at an arbitrary file of the host. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; - List domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)]; + if (!getLibraryResult.Value.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path))) + return DomainErrors.WrittenContent.BookPathMustBeWithinLibraryContentLocations; - List> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!)); - errors = [.. domainGenresResult.Where(genreResult => genreResult.IsFailure).SelectMany(genreResult => genreResult.Errors)]; - if (errors.Count != 0) - return errors; - List domainGenres = [.. domainGenresResult.Select(genre => genre.Value)]; + // Media contributors are referenced by Id and are never created implicitly by adding a book, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; - List> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!)); - errors = [.. domainTagsResult.Where(tagResult => tagResult.IsFailure).SelectMany(tagResult => tagResult.Errors)]; - if (errors.Count != 0) - return errors; - List domainTags = [.. domainTagsResult.Select(tag => tag.Value)]; - - List> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!)); - errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; - if (errors.Count != 0) - return errors; - List domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)]; - - Result releaseInfoResult = ReleaseInfo.Create( - Optional.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate), - Optional.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear), - Optional.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate), - Optional.FromNullable(command.Metadata.ReleaseInfo.ReReleaseYear), - Optional.FromNullable(command.Metadata.ReleaseInfo!.ReleaseCountry), - Optional.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion) - ); - if (releaseInfoResult.IsFailure) - return releaseInfoResult.Errors; - ReleaseInfo releaseInfo = releaseInfoResult.Value; - LanguageInfo? languageInfo = null; - if (command.Metadata.Language is not null) - { - Result languageInfoResult = LanguageInfo.Create( - command.Metadata.Language.LanguageCode!, - command.Metadata.Language.LanguageName!, - Optional.FromNullable(command.Metadata.Language.NativeName)); - if (languageInfoResult.IsFailure) - return languageInfoResult.Errors; - languageInfo = languageInfoResult.Value; - } - LanguageInfo? originalLanguageInfo = null; - if (command.Metadata.OriginalLanguage is not null) - { - Result originalLanguageInfoResult = LanguageInfo.Create( - command.Metadata.OriginalLanguage.LanguageCode!, - command.Metadata.OriginalLanguage.LanguageName!, - Optional.FromNullable(command.Metadata.OriginalLanguage.NativeName)); - if (originalLanguageInfoResult.IsFailure) - return originalLanguageInfoResult.Errors; - originalLanguageInfo = originalLanguageInfoResult.Value; - } - Result metadataResult = WrittenContentMetadata.Create( - command.Metadata.Title!, - Optional.FromNullable(command.Metadata.OriginalTitle), - Optional.FromNullable(command.Metadata.Description), - releaseInfo, - domainGenres, - domainTags, - Optional.FromNullable(languageInfo), - Optional.FromNullable(originalLanguageInfo), - Optional.FromNullable(command.Metadata.Publisher), - Optional.FromNullable(command.Metadata.PageCount) - ); - if (metadataResult.IsFailure) - return metadataResult.Errors; - - // Link the media contributors typed by the user to the book, finding or creating a single contributor per person; the same person - // can be credited under several roles, so every distinct display name must resolve to the same media contributor row. - List contributorIds = []; - Dictionary contributorsByDisplayName = []; - foreach (MediaContributorDto contributor in command.Contributors!) - { - if (contributor.Name?.DisplayName is null) - continue; - - if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity)) - { - Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false); - if (findOrCreateResult.IsFailure) - return findOrCreateResult.Errors; - contributorEntity = findOrCreateResult.Value; - contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity); - } - - contributorIds.Add(MediaContributorId.Create(contributorEntity.Id)); - } - - Result createBookResult = Book.Create( - LibraryId.Create(command.LibraryId), - command.Path, - metadataResult.Value, - Optional.FromNullable(command.Format), - Optional.FromNullable(command.Edition), - command.VolumeNumber ?? default, - Optional.FromNullable(bookSeries), - Optional.FromNullable(command.ASIN), - Optional.FromNullable(command.GoodreadsId), - Optional.FromNullable(command.LCCN), - Optional.FromNullable(command.OCLCNumber), - Optional.FromNullable(command.OpenLibraryId), - Optional.FromNullable(command.LibraryThingId), - Optional.FromNullable(command.GoogleBooksId), - Optional.FromNullable(command.BarnesAndNobleId), - Optional.FromNullable(command.AppleBooksId), - domainIsbns, - contributorIds, - ratings: domainRatings - ); + // Convert the command to a domain aggregate to enforce invariants, then persist it in the repository. + Result createBookResult = command.ToDomainEntity(libraryId); if (createBookResult.IsFailure) return createBookResult.Errors; - // The participation rows need the generated id of the book, so they are built once the domain book exists. - BookEntity persistenceBook = createBookResult.Value.ToRepositoryEntity(); - persistenceBook.CreatedBy = userId; - persistenceBook.BookContributors = [.. command.Contributors! - .Where(contributor => contributor.Name?.DisplayName is not null) - .Select(contributor => new BookContributorEntity - { - Id = Guid.NewGuid(), - BookId = persistenceBook.Id, - MediaContributorId = contributorsByDisplayName[contributor.Name!.DisplayName!].Id, - RoleName = contributor.Role?.Name ?? "Contributor", - RoleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = userId, - UpdatedBy = null - })]; - Result insertBookResult = await _unitOfWork.BookRepository.InsertAsync(persistenceBook, cancellationToken).ConfigureAwait(false); + Result insertBookResult = await _unitOfWork.BookRepository.InsertAsync(createBookResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (insertBookResult.IsFailure) return insertBookResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return persistenceBook.ToResponse() with { Contributors = command.Contributors }; + // The pre-insert checks handle the common cases; a concurrent request could still persist a book at the same path of the same + // library between them and the save, in which case the persistence medium reports the unique constraint violation as a conflict. + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save. + Result getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(createBookResult.Value.Id.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedBookResult.IsFailure) + return getPersistedBookResult.Errors; + if (getPersistedBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + + return getPersistedBookResult.Value.ToResponse(); + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(AddBookCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return DomainErrors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index e782bded..5755cf91 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -18,22 +18,31 @@ public class AddBookCommandValidator : AbstractValidator /// public AddBookCommandValidator() { + // Validates the identifier of the media library that will own the book, taken from the route. RuleFor(command => command.LibraryId) .NotEmpty() - .WithError(Errors.WrittenContent.BookLibraryCannotBeNull) - .Must(id => id != Guid.Empty) - .WithError(Errors.WrittenContent.BookLibraryCannotBeNull); + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + // Validates the file system path of the book. RuleFor(command => command.Path) .NotEmpty() - .WithError(Errors.WrittenContent.BookPathCannotBeEmpty); + .WithError(Errors.WrittenContent.BookPathCannotBeEmpty) + .MaximumLength(2048) + .WithError(Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong); + // Validates the metadata of the book: title, lengths, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) .ChildRules(metadata => { metadata.RuleFor(m => m!.Title) + .NotNull() .NotEmpty() .WithError(Errors.Metadata.TitleCannotBeEmpty) .MaximumLength(255) @@ -117,8 +126,7 @@ public class AddBookCommandValidator : AbstractValidator metadata.RuleFor(m => m!.Tags) .NotNull() .WithError(Errors.Metadata.TagsListCannotBeNull); - - + metadata.RuleForEach(m => m!.Tags) .ChildRules(tag => tag.RuleFor(t => t.Name) @@ -130,7 +138,7 @@ public class AddBookCommandValidator : AbstractValidator metadata.RuleFor(m => m!.Language!.LanguageCode) .NotEmpty() .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) - .MaximumLength(2) + .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.Language is not null); @@ -147,8 +155,9 @@ public class AddBookCommandValidator : AbstractValidator .When(m => m!.Language is not null); metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) - .NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) - .MaximumLength(2) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.OriginalLanguage is not null); @@ -175,6 +184,7 @@ public class AddBookCommandValidator : AbstractValidator .WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); }); + // Validates the physical characteristics of the book: format, edition and volume number. RuleFor(command => command.Format) .IsInEnum() .When(command => command.Format is not null) @@ -190,6 +200,7 @@ public class AddBookCommandValidator : AbstractValidator .When(command => command.VolumeNumber.HasValue) .WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + // Validates the series the book is part of, when the request carries one. RuleFor(command => command.Series) .ChildRules(series => series.RuleFor(s => s!.Title) @@ -199,6 +210,7 @@ public class AddBookCommandValidator : AbstractValidator .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong)) .When(command => command.Series is not null); + // Validates the external identifiers of the book. RuleFor(command => command.ASIN) .Length(10) .When(command => command.ASIN is not null) @@ -249,6 +261,7 @@ public class AddBookCommandValidator : AbstractValidator .When(command => command.AppleBooksId is not null) .WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + // Validates the ISBN list of the book. RuleFor(command => command.ISBNs) .NotNull() .WithError(Errors.WrittenContent.IsbnListCannotBeNull); @@ -274,49 +287,27 @@ public class AddBookCommandValidator : AbstractValidator .IsInEnum() .WithError(Errors.WrittenContent.UnknownIsbnFormat); }); - + + // Validates the media contributors that contributed to the book. RuleFor(command => command.Contributors) .NotNull() .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); - + RuleForEach(command => command.Contributors) .ChildRules(contributor => { - contributor.RuleFor(c => c.Name) - .NotNull() - .WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty) - .ChildRules(name => - { - name.RuleFor(n => n!.DisplayName) - .NotNull() - .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) - .NotEmpty() - .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) - .MaximumLength(100) - .WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); - - name.RuleFor(n => n!.LegalName) - .MaximumLength(100) - .When(n => n!.LegalName is not null) - .WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); - }); - + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + contributor.RuleFor(c => c.Role) - .NotNull() - .WithError(Errors.MediaContributor.ContributorRoleCannotBeNull) - .ChildRules(role => - { - role.RuleFor(r => r!.Name) - .NotEmpty() - .WithError(Errors.MediaContributor.RoleNameCannotBeEmpty) - .MaximumLength(50) - .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); - role.RuleFor(r => r!.Category) - .NotEmpty() - .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); - }); + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); }); + // Validates the ratings of the book. RuleFor(command => command.Ratings) .NotNull() .WithError(Errors.Metadata.RatingsListCannotBeNull); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs index f9650855..459f4159 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommand.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; @@ -14,7 +14,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Command for updating an existing book. /// -/// The Id of the book to update. +/// The unique identifier of the media library this book belongs to, taken from the route. +/// The unique identifier of the book to update, taken from the route. /// Written content metadata of the book. /// The format of the book (e.g., Hardcover, Paperback), if applicable. /// The edition of the book, if applicable. @@ -30,11 +31,12 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// The Barnes & Noble ID of the book, if applicable. /// The Apple Books ID of the book, if applicable. /// The list of ISBN (International Standard Book Number) of the book. -/// The list of media contributors (actors, directors, etc) starring in this book. +/// The list of media contributors that contributed to this book. /// The list of ratings for this book. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateBookCommand( - Guid Id, + string? LibraryId, + string? BookId, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, @@ -50,6 +52,6 @@ public record UpdateBookCommand( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs index c844a210..f6df648b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandHandler.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; 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.UoW; using Lumina.Application.Common.Infrastructure.Authentication; @@ -8,12 +9,9 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Linq; @@ -70,85 +68,87 @@ public class UpdateBookCommandHandler : ICommandHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.WrittenContent.BookNotFound; BookEntity existingBook = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be edited through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (existingBook.LibraryId != libraryId) + return DomainErrors.WrittenContent.BookNotFound; + // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - // Convert the book to a domain object and apply the edited metadata to it. - Result getDomainBookResult = existingBook.ToDomainEntity(); - if (getDomainBookResult.IsFailure) - return getDomainBookResult.Errors; - Book book = getDomainBookResult.Value; + // A book can only belong to a library that exists, so a client can never update a book that points to a library of the host that is not there. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; - Result applyMetadataResult = book.ApplyMetadata(command.ToBookMetadataDto()); - if (applyMetadataResult.IsFailure) - return applyMetadataResult.Errors; + // Media contributors are referenced by Id and are never created implicitly by editing a book, so each one must already exist. + Result> getContributorsResult = await GetExistingContributorsAsync(command, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; - // Link the media contributors typed by the user to the book, finding or creating a single contributor per person. - List linkedContributors = []; - // A person can be credited under several roles in the same book; each distinct display name must resolve to the same media - // contributor row, otherwise the duplicate inserts would violate the unique display name constraint when the changes are saved. - Dictionary contributorsByDisplayName = []; - foreach (MediaContributorDto contributor in command.Contributors!) - { - if (contributor.Name?.DisplayName is null) - continue; - - if (!contributorsByDisplayName.TryGetValue(contributor.Name.DisplayName, out MediaContributorEntity? contributorEntity)) - { - Result findOrCreateResult = await _unitOfWork.MediaContributorRepository.FindOrCreateByDisplayNameAsync(contributor.Name.DisplayName, contributor.Name.LegalName, cancellationToken).ConfigureAwait(false); - if (findOrCreateResult.IsFailure) - return findOrCreateResult.Errors; - contributorEntity = findOrCreateResult.Value; - contributorsByDisplayName.Add(contributor.Name.DisplayName, contributorEntity); - } - - string roleName = contributor.Role?.Name ?? "Contributor"; - MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other; - linkedContributors.Add(new BookContributorEntity - { - Id = Guid.NewGuid(), - BookId = existingBook.Id, - MediaContributorId = contributorEntity.Id, - RoleName = roleName, - RoleCategory = roleCategory, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = userId, - UpdatedBy = null - }); - } - book.UpdateContributors([.. linkedContributors.Select(linkedContributor => MediaContributorId.Create(linkedContributor.MediaContributorId))]); + // Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored book. + Result updateBookResult = command.ToDomainEntity(existingBook); + if (updateBookResult.IsFailure) + return updateBookResult.Errors; // Map the updated domain book onto a fresh repository entity, ready for the repository to replace the stored data. - BookEntity updatedBook = book.ToRepositoryEntity(); - updatedBook.BookContributors = linkedContributors; - updatedBook.UpdatedOnUtc = DateTime.UtcNow; - updatedBook.UpdatedBy = userId; - - // The identity, enrichment and artwork columns are never overwritten by an edit, so they are copied onto the fresh entity that - // backs the response; without this, the response would report the fresh entity defaults (Pending metadata status, no cover path). - updatedBook.CreatedOnUtc = existingBook.CreatedOnUtc; - updatedBook.MetadataStatus = existingBook.MetadataStatus; - updatedBook.LastMetadataUpdateUtc = existingBook.LastMetadataUpdateUtc; - updatedBook.MetadataProvider = existingBook.MetadataProvider; - updatedBook.BookArtwork = existingBook.BookArtwork; + BookEntity updatedBook = updateBookResult.Value.ToRepositoryEntity(); Result updateResult = await _unitOfWork.BookRepository.UpdateAsync(updatedBook, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - return updatedBook.ToResponse() with { Contributors = command.Contributors }; + // Returns the book as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the persistence medium applied on save. + Result getPersistedBookResult = await _unitOfWork.BookRepository.GetByIdAsync(existingBook.Id, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedBookResult.IsFailure) + return getPersistedBookResult.Errors; + if (getPersistedBookResult.Value is null) + return DomainErrors.WrittenContent.BookNotFound; + + return getPersistedBookResult.Value.ToResponse(); + } + + /// + /// Gets the media contributors referenced by , requiring each referenced Id to already exist. + /// + /// The command carrying the referenced media contributors. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the existing media contributors, or an error when at least one referenced contributor does not exist. + /// + private async Task>> GetExistingContributorsAsync(UpdateBookCommand command, CancellationToken cancellationToken) + { + List contributorIds = [.. command.Contributors!.Select(contributor => contributor.ContributorId).Distinct()]; + if (contributorIds.Count == 0) + return Result.From>([]); + + Result> getContributorsResult = await _unitOfWork.MediaContributorRepository + .GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); + if (getContributorsResult.IsFailure) + return getContributorsResult.Errors; + if (getContributorsResult.Value.Count != contributorIds.Count) + return DomainErrors.MediaContributor.MediaContributorNotFound; + return Result.From(getContributorsResult.Value); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs index 3f3de404..99238a80 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandValidator.cs @@ -18,18 +18,34 @@ public class UpdateBookCommandValidator : AbstractValidator /// public UpdateBookCommandValidator() { - RuleFor(command => command.Id) + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book to update, taken from the route. + RuleFor(command => command.BookId) .NotEmpty() - .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) - .Must(id => id != Guid.Empty) .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + RuleFor(command => command.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(command => command.BookId is not null && command.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + // Validates the metadata of the book: title, lengths, release information, languages, genres and tags. RuleFor(command => command.Metadata) .NotNull() .WithError(Errors.Metadata.MetadataCannotBeNull) .ChildRules(metadata => { metadata.RuleFor(m => m!.Title) + .NotNull() .NotEmpty() .WithError(Errors.Metadata.TitleCannotBeEmpty) .MaximumLength(255) @@ -125,7 +141,7 @@ public class UpdateBookCommandValidator : AbstractValidator metadata.RuleFor(m => m!.Language!.LanguageCode) .NotEmpty() .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) - .MaximumLength(2) + .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.Language is not null); @@ -144,7 +160,7 @@ public class UpdateBookCommandValidator : AbstractValidator metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) .NotEmpty() .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) - .MaximumLength(2) + .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.OriginalLanguage is not null); @@ -171,6 +187,7 @@ public class UpdateBookCommandValidator : AbstractValidator .WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); }); + // Validates the physical characteristics of the book: format, edition and volume number. RuleFor(command => command.Format) .IsInEnum() .When(command => command.Format is not null) @@ -186,6 +203,7 @@ public class UpdateBookCommandValidator : AbstractValidator .When(command => command.VolumeNumber.HasValue) .WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + // Validates the series the book is part of, when the request carries one. RuleFor(command => command.Series) .ChildRules(series => series.RuleFor(s => s!.Title) @@ -195,6 +213,7 @@ public class UpdateBookCommandValidator : AbstractValidator .WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong)) .When(command => command.Series is not null); + // Validates the external identifiers of the book. RuleFor(command => command.ASIN) .Length(10) .When(command => command.ASIN is not null) @@ -227,25 +246,24 @@ public class UpdateBookCommandValidator : AbstractValidator RuleFor(command => command.GoogleBooksId) .Length(12) - .When(command => command.GoogleBooksId is not null) .WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong) .Matches(@"^[A-Za-z0-9_-]{12}$") - .When(command => command.GoogleBooksId is not null) - .WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat); + .WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat) + .When(command => command.GoogleBooksId is not null); RuleFor(command => command.BarnesAndNobleId) .Length(10) - .When(command => command.BarnesAndNobleId is not null) .WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong) .Matches(@"^\d{10}$") - .When(command => command.BarnesAndNobleId is not null) - .WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat); + .WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat) + .When(command => command.BarnesAndNobleId is not null); RuleFor(command => command.AppleBooksId) .Matches(@"^id\d+$") .When(command => command.AppleBooksId is not null) .WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + // Validates the ISBN list of the book. RuleFor(command => command.ISBNs) .NotNull() .WithError(Errors.WrittenContent.IsbnListCannotBeNull); @@ -272,6 +290,7 @@ public class UpdateBookCommandValidator : AbstractValidator .WithError(Errors.WrittenContent.UnknownIsbnFormat); }); + // Validates the media contributors that contributed to the book. RuleFor(command => command.Contributors) .NotNull() .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); @@ -279,41 +298,18 @@ public class UpdateBookCommandValidator : AbstractValidator RuleForEach(command => command.Contributors) .ChildRules(contributor => { - contributor.RuleFor(c => c.Name) - .NotNull() - .WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty) - .ChildRules(name => - { - name.RuleFor(n => n!.DisplayName) - .NotNull() - .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) - .NotEmpty() - .WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty) - .MaximumLength(100) - .WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); - - name.RuleFor(n => n!.LegalName) - .MaximumLength(100) - .When(n => n!.LegalName is not null) - .WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); - }); + contributor.RuleFor(c => c.ContributorId) + .NotEmpty() + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty) + .Must(contributorId => contributorId != Guid.Empty) + .WithError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); contributor.RuleFor(c => c.Role) - .NotNull() - .WithError(Errors.MediaContributor.ContributorRoleCannotBeNull) - .ChildRules(role => - { - role.RuleFor(r => r!.Name) - .NotEmpty() - .WithError(Errors.MediaContributor.RoleNameCannotBeEmpty) - .MaximumLength(50) - .WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); - role.RuleFor(r => r!.Category) - .NotEmpty() - .WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); - }); + .IsInEnum() + .WithError(Errors.MediaContributor.UnknownMediaContributorRole); }); + // Validates the ratings of the book. RuleFor(command => command.Ratings) .NotNull() .WithError(Errors.Metadata.RatingsListCannotBeNull); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs index 9921e03d..1c2715d0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; using System.Diagnostics; using System.IO; #endregion @@ -10,12 +9,14 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Command for updating the cover image of an existing book. /// -/// The Id of the book whose cover image is updated. +/// The unique identifier of the media library this book belongs to, taken from the route. +/// The unique identifier of the book whose cover image is updated, taken from the route. /// The stream of the uploaded cover image file. /// The name of the uploaded cover image file. [DebuggerDisplay("BookId: {BookId} FileName: {FileName}")] public record UpdateBookCoverCommand( - Guid BookId, + string? LibraryId, + string? BookId, Stream? Cover, string? FileName ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs index df4d26db..b97b4a16 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandHandler.cs @@ -8,9 +8,10 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; @@ -27,7 +28,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Handler for the command to update the cover image of an existing book. /// -public class UpdateBookCoverCommandHandler : ICommandHandler> +public class UpdateBookCoverCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; private readonly IBookArtworkService _bookArtworkService; @@ -58,9 +59,9 @@ public class UpdateBookCoverCommandHandler : ICommandHandlerThe command to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either the relative path of the stored cover image, or an error message. + /// An containing either the response carrying the relative path of the stored cover image, or an error message. /// - public async Task> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken) + public async Task> HandleAsync(UpdateBookCoverCommand command, CancellationToken cancellationToken) { List validationResult = _validator.Validate(command); if (validationResult.Count > 0) @@ -72,14 +73,23 @@ public class UpdateBookCoverCommandHandler : ICommandHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(command.BookId, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.WrittenContent.BookNotFound; BookEntity existingBook = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be edited through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (existingBook.LibraryId != libraryId) + return DomainErrors.WrittenContent.BookNotFound; + // Admins can update the books of all libraries; for everyone else, only the books of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); @@ -87,13 +97,16 @@ public class UpdateBookCoverCommandHandler : ICommandHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) return DomainErrors.Library.LibraryNotFound; string libraryName = getLibraryResult.Value.Title; - string authorName = await GetAuthorNameAsync(existingBook, cancellationToken).ConfigureAwait(false); + Result authorNameResult = await GetAuthorNameAsync(existingBook, cancellationToken).ConfigureAwait(false); + if (authorNameResult.IsFailure) + return authorNameResult.Errors; + string authorName = authorNameResult.Value; Result storeArtworkResult = await _bookArtworkService.SaveBookArtworkAsync( existingBook.LibraryId, @@ -107,35 +120,17 @@ public class UpdateBookCoverCommandHandler : ICommandHandler artwork.ArtworkType == ArtworkType.Cover); - if (coverArtwork is null) - { - existingBook.BookArtwork.Add(new BookArtworkEntity - { - Id = Guid.NewGuid(), - BookId = existingBook.Id, - ArtworkType = ArtworkType.Cover, - Ordinal = 0, - FileName = storeArtworkResult.Value, - Status = ArtworkStatus.Enriched, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = userId, - UpdatedBy = null - }); - } - else - { - coverArtwork.FileName = storeArtworkResult.Value; - coverArtwork.Status = ArtworkStatus.Enriched; - coverArtwork.LastUpdateUtc = DateTime.UtcNow; - coverArtwork.UpdatedOnUtc = DateTime.UtcNow; - coverArtwork.UpdatedBy = userId; - } + // Map the newly stored cover image onto the artwork of the book, replacing the existing cover or adding a new one. + BookArtworkEntity? existingCover = existingBook.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover); + BookArtworkEntity coverArtwork = command.ToRepositoryEntity(existingCover, bookId, storeArtworkResult.Value, userId); + if (existingCover is null) + existingBook.Artwork.Add(coverArtwork); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; - return storeArtworkResult.Value; + return new UpdateBookCoverResponse(storeArtworkResult.Value); } /// @@ -143,19 +138,21 @@ public class UpdateBookCoverCommandHandler : ICommandHandler /// The book whose author is retrieved. /// Cancellation token that can be used to stop the execution. - /// The display name of the author of the book, or an empty string. - private async Task GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken) + /// + /// An containing either the display name of the author of the book, or an error when the referenced media contributors could not be retrieved. + /// + private async Task> GetAuthorNameAsync(BookEntity book, CancellationToken cancellationToken) { - IReadOnlyCollection authorIds = [.. book.BookContributors - .Where(participation => participation.RoleCategory == MediaContributorRoleCategory.Author) + IReadOnlyCollection authorIds = [.. book.Contributors + .Where(participation => participation.Role == MediaContributorRole.Author) .Select(participation => participation.MediaContributorId) .Distinct()]; if (authorIds.Count == 0) - return string.Empty; + return Result.From(string.Empty); Result> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false); if (getContributorsResult.IsFailure) - return string.Empty; - return getContributorsResult.Value.Select(contributor => contributor.DisplayName).FirstOrDefault() ?? string.Empty; + return getContributorsResult.Errors; + return Result.From(getContributorsResult.Value.Select(contributor => contributor.DisplayName).FirstOrDefault() ?? string.Empty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs index 3333a4e4..7ee985bb 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandValidator.cs @@ -17,14 +17,34 @@ public class UpdateBookCoverCommandValidator : AbstractValidator public UpdateBookCoverCommandValidator() { + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(command => command.LibraryId is not null && command.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book whose cover image is updated, taken from the route. RuleFor(command => command.BookId) .NotEmpty() - .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) - .Must(id => id != Guid.Empty) .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + RuleFor(command => command.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(command => command.BookId is not null && command.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + // Validates the uploaded cover image. RuleFor(command => command.Cover) .NotNull() .WithError(Errors.WrittenContent.BookCoverCannotBeNull); + + RuleFor(command => command.FileName) + .NotEmpty() + .When(command => command.Cover is not null) + .WithError(Errors.FileSystemManagement.FileNameCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs index e4ed13d0..0fe84775 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; @@ -8,7 +7,9 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting a book by its Id. /// -/// The Id of the book to get. +/// The unique identifier of the media library the book belongs to, taken from the route. +/// The unique identifier of the book to get, taken from the route. public record GetBookQuery( - Guid Id + string? LibraryId, + string? BookId ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs index 683bd388..bf4d1617 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandler.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; @@ -8,12 +7,10 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -67,56 +64,29 @@ public class GetBookQueryHandler : IQueryHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.WrittenContent.BookNotFound; + BookEntity existingBook = getBookResult.Value; + + // Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (existingBook.LibraryId != libraryId) + return DomainErrors.WrittenContent.BookNotFound; // Admins can see the books of all libraries; for everyone else, only the books of the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(getBookResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - BookResponse response = getBookResult.Value.ToResponse(); - - // The response carries the resolved contributor names, so that the clients can display them without querying the contributors themselves. - List contributors = await GetContributorsAsync(getBookResult.Value, cancellationToken).ConfigureAwait(false); - if (contributors.Count == 0) - return response; - - Dictionary contributorsById = contributors.ToDictionary(contributor => contributor.Id); - List contributorResponses = []; - foreach (BookContributorEntity participation in getBookResult.Value.BookContributors) - { - if (!contributorsById.TryGetValue(participation.MediaContributorId, out MediaContributorEntity? contributor)) - continue; - contributorResponses.Add(new MediaContributorDto( - new MediaContributorNameDto(contributor.DisplayName, contributor.LegalName), - new MediaContributorRoleDto(participation.RoleName, participation.RoleCategory) - )); - } - - return response with { Contributors = contributorResponses }; - } - - /// - /// Gets the media contributors linked to the book of , by their unique identifiers. - /// - /// The book whose media contributors are retrieved. - /// Cancellation token that can be used to stop the execution. - /// An containing either the media contributors of the book, or an error. - private async Task> GetContributorsAsync(BookEntity book, CancellationToken cancellationToken) - { - IReadOnlyCollection contributorIds = [.. book.BookContributors.Select(participation => participation.MediaContributorId).Distinct()]; - if (contributorIds.Count == 0) - return []; - - Result> getContributorsResult = await _unitOfWork.MediaContributorRepository.GetByIdsAsync(contributorIds, cancellationToken).ConfigureAwait(false); - if (getContributorsResult.IsFailure) - return []; - return [.. getContributorsResult.Value]; + return existingBook.ToResponse(); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs index 43ba1eaa..a617584c 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryValidator.cs @@ -17,10 +17,24 @@ public class GetBookQueryValidator : AbstractValidator /// public GetBookQueryValidator() { - RuleFor(query => query.Id) + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(query => query.LibraryId) .NotEmpty() - .WithError(Errors.WrittenContent.BookIdCannotBeEmpty) - .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book to get, taken from the route. + RuleFor(query => query.BookId) + .NotEmpty() + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + RuleFor(query => query.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(query => query.BookId is not null && query.BookId.Length > 0) .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs index 480017ba..624241ea 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; #endregion @@ -10,13 +9,15 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting all the books of a media library. /// +/// The unique identifier of the media library whose books are retrieved, taken from the route. /// The object containing the requested pagination data. -/// The object containing the criteria used to filter the results. +/// The search term used to filter results. /// The name of the field by which to sort the results. /// The direction in which to sort the results. public record GetBooksQuery( + string? LibraryId, PaginationDataDto? PaginationData, - LibraryFilterDto Filter, + string? SearchTerm, string? SortBy, SortOrder? SortOrder ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index c75ec08b..4893c169 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs @@ -2,7 +2,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; #endregion @@ -60,25 +61,34 @@ public class GetBooksQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can see all libraries; for everyone else, only the libraries they own + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false); + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return Errors.Authorization.NotAuthorized; - // get all books of the media library from the book repository - Result> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync( + // Get all books of the media library from the book repository. + LibraryFilterDto libraryFilter = new() + { + LibraryId = libraryId, + SearchTerm = query.SearchTerm + }; + Result> getBooksResult = await _unitOfWork.BookRepository.GetAllAsync( query.PaginationData, query.SortBy, query.SortOrder, - query.Filter, - cancellationToken).ConfigureAwait(false); + libraryFilter, + shouldTrackEntities: false, + cancellationToken: cancellationToken).ConfigureAwait(false); return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs index d091269c..efa69a03 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidator.cs @@ -17,10 +17,14 @@ public class GetBooksQueryValidator : AbstractValidator /// public GetBooksQueryValidator() { - RuleFor(query => query.Filter.LibraryId) + // Validates the identifier of the media library whose books are retrieved, taken from the route. + RuleFor(query => query.LibraryId) .NotEmpty() - .WithError(Errors.Library.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) .WithError(Errors.Library.LibraryIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs index 87dd8ef0..8c5f420b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; #endregion @@ -10,13 +9,19 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting the lightweight details of all the books of a media library. /// +/// The unique identifier of the media library whose books are retrieved, taken from the route. /// The object containing the requested pagination data. -/// The object containing the criteria used to filter the results. +/// The search term used to filter results. +/// The alpha key used to filter results by the first character of their title. +/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// The name of the field by which to sort the results. /// The direction in which to sort the results. public record GetBooksLiteQuery( + string? LibraryId, PaginationDataDto? PaginationData, - LibraryFilterDto Filter, + string? SearchTerm, + string? FilterAlphaKey, + bool ShouldIgnoreThePrefixForAlphaPicker, string? SortBy, SortOrder? SortOrder ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs index 79c58486..9e77a990 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandler.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -16,6 +16,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Errors; +using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; #endregion @@ -60,25 +61,37 @@ public class GetBooksLiteQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can see all libraries; for everyone else, only the libraries they own + // The validator guarantees that the library id of the route is a non-empty Guid before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + + // Admins can see all libraries; for everyone else, only the libraries they own. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( - userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false); + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return Errors.Authorization.NotAuthorized; - // get all books of the media library from the book repository - Result> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync( + LibraryFilterDto libraryFilter = new() + { + LibraryId = libraryId, + SearchTerm = query.SearchTerm, + FilterAlphaKey = query.FilterAlphaKey, + ShouldIgnoreThePrefixForAlphaPicker = query.ShouldIgnoreThePrefixForAlphaPicker + }; + + // Get the lightweight read models of the books of the media library from the book repository, projecting only the fields needed for a grid or a list. + Result> getBooksResult = await _unitOfWork.BookRepository.GetAllLiteAsync( query.PaginationData, query.SortBy, query.SortOrder, - query.Filter, - cancellationToken).ConfigureAwait(false); - return getBooksResult.Match(value => Result.From(value.ToLiteResponses()), errors => errors); + libraryFilter, + shouldTrackEntities: false, + cancellationToken: cancellationToken).ConfigureAwait(false); + return getBooksResult.Match(value => Result.From(value.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs index ba7c48eb..922713b8 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidator.cs @@ -18,15 +18,19 @@ public class GetBooksLiteQueryValidator : AbstractValidator /// public GetBooksLiteQueryValidator() { - RuleFor(query => query.Filter.LibraryId) + // Validates the identifier of the media library whose books are retrieved, taken from the route. + RuleFor(query => query.LibraryId) .NotEmpty() - .WithError(Errors.Library.LibraryIdCannotBeEmpty) - .Must(id => id != Guid.Empty) .WithError(Errors.Library.LibraryIdCannotBeEmpty); - // the alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can - // derive the key of a title unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter - RuleFor(query => query.Filter.FilterAlphaKey) + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // The alpha key must be exactly one of the three picker bucket kinds, so that the filter specification can + // derive the key of a title unambiguously: no filter, a number bucket, a symbol bucket, or a single ASCII letter. + RuleFor(query => query.FilterAlphaKey) .Must(alphaKey => alphaKey is null || alphaKey == LibraryItemAlphaKeys.NUMBER || alphaKey == LibraryItemAlphaKeys.SYMBOL diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs index 94ab3754..98fa454d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; @@ -8,7 +7,9 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for checking the reading availability of a book. /// -/// The Id of the book whose reading availability is checked. +/// The unique identifier of the media library the book belongs to, taken from the route. +/// The unique identifier of the book whose reading availability is checked, taken from the route. public record GetReadingAvailabilityQuery( - Guid BookId + string? LibraryId, + string? BookId ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs index b1d8b9c4..e8892cf6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandler.cs @@ -68,22 +68,31 @@ public class GetReadingAvailabilityQueryHandler : IQueryHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.Reading.BookNotFound; BookEntity book = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (book.LibraryId != libraryId) + return DomainErrors.Reading.BookNotFound; + // Admins can read the books of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs index 8207145e..c96b0709 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidator.cs @@ -17,8 +17,24 @@ public class GetReadingAvailabilityQueryValidator : AbstractValidator public GetReadingAvailabilityQueryValidator() { + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book whose reading availability is checked, taken from the route. RuleFor(query => query.BookId) .NotEmpty() - .WithError(Errors.Reading.BookIdCannotBeEmpty); + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + RuleFor(query => query.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(query => query.BookId is not null && query.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs index ebae8e5b..85b20957 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; @@ -8,7 +7,9 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting the reading manifest of a book. /// -/// The Id of the book whose reading manifest is retrieved. +/// The unique identifier of the media library the book belongs to, taken from the route. +/// The unique identifier of the book whose reading manifest is retrieved, taken from the route. public record GetReadingManifestQuery( - Guid BookId + string? LibraryId, + string? BookId ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs index 302c74f3..d2d0cb9b 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandler.cs @@ -69,22 +69,31 @@ public class GetReadingManifestQueryHandler : IQueryHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.Reading.BookNotFound; BookEntity book = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (book.LibraryId != libraryId) + return DomainErrors.Reading.BookNotFound; + // Admins can read the books of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs index 27e12875..6e623745 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidator.cs @@ -17,8 +17,24 @@ public class GetReadingManifestQueryValidator : AbstractValidator public GetReadingManifestQueryValidator() { + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book whose reading manifest is retrieved, taken from the route. RuleFor(query => query.BookId) .NotEmpty() - .WithError(Errors.Reading.BookIdCannotBeEmpty); + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + RuleFor(query => query.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(query => query.BookId is not null && query.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs index 1de80056..f245eb44 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; @@ -8,9 +7,11 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting a resource of a book, for reading. /// -/// The Id of the book whose resource is retrieved. -/// The opaque resource key of the resource. +/// The unique identifier of the media library the book belongs to, taken from the route. +/// The unique identifier of the book whose resource is retrieved, taken from the route. +/// The opaque resource key of the resource, taken from the route. public record GetReadingResourceQuery( - Guid BookId, - string ResourceKey + string? LibraryId, + string? BookId, + string? ResourceKey ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs index 83f9c772..86ee49e1 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandler.cs @@ -69,21 +69,30 @@ public class GetReadingResourceQueryHandler : IQueryHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.Reading.BookNotFound; BookEntity book = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (book.LibraryId != libraryId) + return DomainErrors.Reading.BookNotFound; + // Admins can read the books of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) @@ -97,6 +106,6 @@ public class GetReadingResourceQueryHandler : IQueryHandler public GetReadingResourceQueryValidator() { + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book whose resource is retrieved, taken from the route. RuleFor(query => query.BookId) .NotEmpty() - .WithError(Errors.Reading.BookIdCannotBeEmpty); + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + RuleFor(query => query.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(query => query.BookId is not null && query.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + // Validates the opaque resource key of the resource, taken from the route. RuleFor(query => query.ResourceKey) .NotEmpty() .WithError(Errors.Reading.ResourceKeyCannotBeEmpty); diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs index 62b4e2b9..54a67fca 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQuery.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; @@ -8,9 +7,11 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary /// /// Query for getting the content of a reading section of a book. /// -/// The Id of the book whose reading section is retrieved. -/// The opaque location reference of the reading section. +/// The unique identifier of the media library the book belongs to, taken from the route. +/// The unique identifier of the book whose reading section is retrieved, taken from the route. +/// The opaque location reference of the reading section, taken from the route. public record GetReadingSectionQuery( - Guid BookId, - string LocationRef + string? LibraryId, + string? BookId, + string? LocationRef ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs index fb1ca0c5..2d697179 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandler.cs @@ -69,22 +69,31 @@ public class GetReadingSectionQueryHandler : IQueryHandler getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false); + Result getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getBookResult.IsFailure) return getBookResult.Errors; if (getBookResult.Value is null) return DomainErrors.Reading.BookNotFound; BookEntity book = getBookResult.Value; + // Resource scoping: the book must belong to the library named by the route, so that a book can never be read through another + // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library. + if (book.LibraryId != libraryId) + return DomainErrors.Reading.BookNotFound; + // Admins can read the books of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false); + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure) return getLibraryResult.Errors; if (getLibraryResult.Value is null) @@ -100,6 +109,6 @@ public class GetReadingSectionQueryHandler : IQueryHandler public GetReadingSectionQueryValidator() { + // Validates the identifier of the media library the book belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the book whose reading section is retrieved, taken from the route. RuleFor(query => query.BookId) .NotEmpty() - .WithError(Errors.Reading.BookIdCannotBeEmpty); + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + RuleFor(query => query.BookId) + .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty) + .When(query => query.BookId is not null && query.BookId.Length > 0) + .WithError(Errors.WrittenContent.BookIdCannotBeEmpty); + + // Validates the opaque location reference of the reading section, taken from the route. RuleFor(query => query.LocationRef) .NotEmpty() .WithError(Errors.Reading.LocationRefCannotBeEmpty); diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs index eff8b941..8c713a6b 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs @@ -57,23 +57,26 @@ public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can reorder the artwork providers of any library; for everyone else, only their own libraries + // Admins can reorder the artwork providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the artwork provider configurations that are currently registered for the library, so that only providers it actually has are reordered. Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; + // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. for (int rank = 0; rank < command.PluginIds.Count; rank++) { Guid pluginId = command.PluginIds[rank]; @@ -86,7 +89,10 @@ public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index 8fc10e5b..3b3133c8 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -56,23 +56,26 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can reorder the metadata providers of any library; for everyone else, only their own libraries + // Admins can reorder the metadata providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the metadata provider configurations that are currently registered for the library, so that only providers it actually has are reordered. Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; + // Index the configurations by plugin id, so that each requested plugin can be matched without repeatedly searching the list. Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + // Walk the requested order and assign each provider the 1-based rank that matches its position in the command, so the persisted order follows the user's choice. for (int rank = 0; rank < command.PluginIds.Count; rank++) { Guid pluginId = command.PluginIds[rank]; @@ -85,7 +88,10 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs index c1974e81..09b304db 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs @@ -56,18 +56,19 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can configure the artwork providers of any library; for everyone else, only their own libraries + // Admins can configure the artwork providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; @@ -75,12 +76,13 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; @@ -98,10 +100,14 @@ public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs index aa8c8749..6ff5d6c9 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledCommandHandler.cs @@ -97,7 +97,9 @@ public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here, // so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire. _enablementCache.Invalidate(command.LibraryId, command.PluginId); diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index 21e21978..526852b2 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -56,18 +56,19 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can configure the metadata providers of any library; for everyone else, only their own libraries + // Admins can configure the metadata providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Look up the configuration of this provider for the library, so that an existing one is toggled instead of duplicated. Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; @@ -75,12 +76,13 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; @@ -98,10 +100,14 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs index 780748dc..5231bd97 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandler.cs @@ -49,7 +49,11 @@ public class UpdatePluginSettingsCommandHandler : ICommandHandler updateResult = await _unitOfWork.PluginRepository.UpdateSettingsAsync(command.PluginId, settingsJson, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return Result.Success; } } diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs index e5f518db..25658eb6 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -58,28 +60,30 @@ public class GetLibraryArtworkProvidersQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can read the artwork providers of any library; for everyone else, only their own libraries + // Admins can read the artwork providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the artwork provider configurations registered for the library, so that only the providers it actually has are returned. Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; - // build a plugin name lookup from the detected plugins - Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Build a plugin name lookup from the detected plugins, so that each configuration can be returned with its provider's display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) return getPluginsResult.Errors; - Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + // Return the configurations ordered by their rank, so the client sees the providers in the order they are applied. return getConfigurationsResult.Value .OrderBy(configuration => configuration.Rank) .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs index d379ee7f..9df0ee8e 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryBookReaders/GetLibraryBookReadersQueryHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -79,10 +81,10 @@ public class GetLibraryBookReadersQueryHandler : IQueryHandler> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) return getPluginsResult.Errors; - Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); IReadOnlyDictionary> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId(); diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 0143c65c..aab473ae 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -62,28 +64,30 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // admins can read the metadata providers of any library; for everyone else, only their own libraries + // Admins can read the metadata providers of any library; for everyone else, only their own libraries. bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); if (!canAccessLibrary) return ApplicationErrors.Authorization.NotAuthorized; + // Load the metadata provider configurations registered for the library, so that only the providers it actually has are returned. Result> getConfigurationsResult = await _providerConfigurationStore.GetConfigurationsAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; - // build a plugin name lookup from the detected plugins - Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Build a plugin name lookup from the detected plugins, so that each configuration can be returned with its provider's display name. + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) return getPluginsResult.Errors; - Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + Dictionary pluginNames = getPluginsResult.Value.Data.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + // Return the configurations ordered by their rank, so the client sees the providers in the order they are applied. return getConfigurationsResult.Value .OrderBy(configuration => configuration.Rank) .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs index 28a8eae3..f69e02fa 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -53,14 +53,14 @@ public class GetPluginSettingsQueryHandler : IQueryHandler 0) return validationResult; - Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); + Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginResult.IsFailure) return getPluginResult.Errors; PluginEntity? pluginEntity = getPluginResult.Value; if (pluginEntity is null) return Errors.Plugins.PluginNotFound; - // the schema comes from the loaded plugin, the current values from the storage medium + // The schema comes from the loaded plugin, the current values from the storage medium. IPlugin? loadedPlugin = _pluginManager.GetPlugin(query.PluginId); IReadOnlyList schema = loadedPlugin is not null ? loadedPlugin.GetSettingsSchema().Select(setting => setting.ToResponse()).ToList() diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs index df20f182..eb2abe49 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandler.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; using System.Collections.Generic; @@ -40,7 +42,7 @@ public class GetPluginsQueryHandler : IQueryHandler public async Task>> HandleAsync(GetPluginsQuery query, CancellationToken cancellationToken) { - Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getPluginsResult.Match(plugins => Result.From>([.. plugins.Select(plugin => plugin.ToResponse())]), errors => errors); + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + return getPluginsResult.Match(plugins => Result.From>([.. plugins.Data.Select(plugin => plugin.ToResponse())]), errors => errors); } } diff --git a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs index 02151efa..64cb0016 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandler.cs @@ -118,7 +118,10 @@ public class AddScheduledJobCommandHandler : ICommandHandler insertScheduledJobResult = await _unitOfWork.ScheduledJobRepository.InsertAsync(persistenceScheduledJob, cancellationToken).ConfigureAwait(false); if (insertScheduledJobResult.IsFailure) return insertScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Queue any domain events. foreach (IDomainEvent domainEvent in createScheduledJobResult.Value.GetDomainEvents()) diff --git a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs index 86585082..755d2572 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandler.cs @@ -79,7 +79,7 @@ public class FireScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) diff --git a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs index ba19721c..7c843186 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandler.cs @@ -83,7 +83,7 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) @@ -102,7 +102,10 @@ public class RemoveScheduledJobCommandHandler : ICommandHandler deleteScheduledJobResult = await _unitOfWork.ScheduledJobRepository.DeleteByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); if (deleteScheduledJobResult.IsFailure) return deleteScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Queue any domain events. scheduledJobDomainResult.Value.Remove(); diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs index f5c0be2f..d69614f7 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandler.cs @@ -80,7 +80,7 @@ public class StartScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) @@ -98,7 +98,10 @@ public class StartScheduledJobCommandHandler : ICommandHandler updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) return updateScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Queue any domain events. foreach (IDomainEvent domainEvent in scheduledJobDomainResult.Value.GetDomainEvents()) diff --git a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs index 177e0865..af1b937c 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandler.cs @@ -84,7 +84,7 @@ public class StopScheduledJobCommandHandler : ICommandHandler getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) return getScheduledJobResult.Errors; if (getScheduledJobResult.Value is null) @@ -102,7 +102,10 @@ public class StopScheduledJobCommandHandler : ICommandHandler updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(scheduledJobDomainResult.Value.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) return updateScheduledJobResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; // Stop the execution cycle in the scheduler service. await _scheduledJobScheduler.StopCycleAsync(scheduledJobDomainResult.Value.Id, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs index 54c6fa4b..c3634b7e 100644 --- a/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandler.cs @@ -80,7 +80,11 @@ public class UpdateSchedulerDisplayPreferencesCommandHandler : ICommandHandler upsertResult = await _unitOfWork.SchedulerDisplayPreferencesRepository.UpsertAsync(displayPreferences, cancellationToken).ConfigureAwait(false); if (upsertResult.IsFailure) return upsertResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return Result.Updated; } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs index 4a523bd2..fe21598f 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -42,10 +44,10 @@ public class ScheduledJobAddedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(ScheduledJobAddedDomainEvent domainEvent, CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs index 974f02ed..767f1420 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; @@ -49,10 +51,10 @@ public class ScheduledJobCycleStartedDomainEventHandler : IDomainEventHandler> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs index a04da146..9f89647c 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -42,10 +44,10 @@ public class ScheduledJobCycleStoppedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(ScheduledJobCycleStoppedDomainEvent domainEvent, CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs index 6d2df8ee..b2dd7aa8 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -10,7 +12,6 @@ using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; -using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -46,7 +47,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand public async ValueTask HandleAsync(ScheduledJobExecutionCompletedDomainEvent domainEvent, CancellationToken cancellationToken) { // Get the scheduled job from the repository. - Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors); if (getScheduledJobResult.Value is null) @@ -55,94 +56,42 @@ public class ScheduledJobExecutionCompletedDomainEventHandler : IDomainEventHand // A cycle run returns the scheduled job to its active status, a one time execution completes it. ScheduledJobStatus status = domainEvent.IsCycleRun ? ScheduledJobStatus.Active : ScheduledJobStatus.Completed; - ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc); + ScheduledJobEntity updatedScheduledJob = scheduledJob.ToUpdatedRepositoryEntity(status, scheduledJob.LastStartedOnUtc, domainEvent.CompletedOnUtc); Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors); // Mark the execution of the task of the scheduled job as completed. - Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken).ConfigureAwait(false); + Result getExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getExecutionResult.IsFailure) throw new EventualConsistencyException(getExecutionResult.FirstError, getExecutionResult.Errors); if (getExecutionResult.Value is null) throw new EventualConsistencyException(Errors.Scheduling.ScheduledJobExecutionNotFound); ScheduledJobExecutionEntity execution = getExecutionResult.Value; - ScheduledJobExecutionEntity updatedExecution = CreateUpdatedExecution(execution, domainEvent.CompletedOnUtc); + ScheduledJobExecutionEntity updatedExecution = execution.ToUpdatedRepositoryEntity(domainEvent.CompletedOnUtc); Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false); if (updateExecutionResult.IsFailure) throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); // Notify the SignalR clients about the current scheduled jobs and the completed execution. await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false); await _scheduledJobNotifier.SendScheduledJobExecutionCompletedAsync(updatedExecution.ToResponse(), cancellationToken).ConfigureAwait(false); } - /// - /// Creates a copy of with the provided status and timestamps. - /// - /// The scheduled job to copy. - /// The status of the copy. - /// The last start time of the copy. - /// The last completion time of the copy. - /// The copy of the scheduled job. - private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) - { - return new ScheduledJobEntity - { - Id = scheduledJob.Id, - Name = scheduledJob.Name, - TaskType = scheduledJob.TaskType, - ScheduleType = scheduledJob.ScheduleType, - IntervalMinutes = scheduledJob.IntervalMinutes, - Hour = scheduledJob.Hour, - Minute = scheduledJob.Minute, - Status = status, - OwnerUserId = scheduledJob.OwnerUserId, - LastStartedOnUtc = lastStartedOnUtc, - LastCompletedOnUtc = lastCompletedOnUtc, - CreatedOnUtc = scheduledJob.CreatedOnUtc, - CreatedBy = scheduledJob.CreatedBy, - UpdatedOnUtc = scheduledJob.UpdatedOnUtc, - UpdatedBy = scheduledJob.UpdatedBy - }; - } - - /// - /// Creates a copy of with the provided completion time. - /// - /// The execution to copy. - /// The completion time of the copy. - /// The copy of the execution. - private static ScheduledJobExecutionEntity CreateUpdatedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) - { - return new ScheduledJobExecutionEntity - { - Id = execution.Id, - ScheduledJobId = execution.ScheduledJobId, - TaskType = execution.TaskType, - IsCycleRun = execution.IsCycleRun, - WasCycleActive = execution.WasCycleActive, - StartedOnUtc = execution.StartedOnUtc, - CompletedOnUtc = completedOnUtc, - CreatedOnUtc = execution.CreatedOnUtc, - CreatedBy = execution.CreatedBy, - UpdatedOnUtc = execution.UpdatedOnUtc, - UpdatedBy = execution.UpdatedBy - }; - } - /// /// Notifies the SignalR clients about the current list of scheduled jobs. /// /// Cancellation token that can be used to stop the execution. private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs index 2e81591f..19dba01a 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -10,7 +12,6 @@ using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; -using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -46,7 +47,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle public async ValueTask HandleAsync(ScheduledJobExecutionStartedDomainEvent domainEvent, CancellationToken cancellationToken) { // Get the scheduled job from the repository. - Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await _unitOfWork.ScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure) throw new EventualConsistencyException(getScheduledJobResult.FirstError, getScheduledJobResult.Errors); if (getScheduledJobResult.Value is null) @@ -57,7 +58,7 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle bool wasCycleActive = scheduledJob.Status == ScheduledJobStatus.Active; // Update the scheduled job with its running status and the start time of the execution. - ScheduledJobEntity updatedScheduledJob = CreateUpdatedScheduledJob(scheduledJob, ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc); + ScheduledJobEntity updatedScheduledJob = scheduledJob.ToUpdatedRepositoryEntity(ScheduledJobStatus.Running, domainEvent.StartedOnUtc, scheduledJob.LastCompletedOnUtc); Result updateScheduledJobResult = await _unitOfWork.ScheduledJobRepository.UpdateAsync(updatedScheduledJob, cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) throw new EventualConsistencyException(updateScheduledJobResult.FirstError, updateScheduledJobResult.Errors); @@ -81,53 +82,25 @@ public class ScheduledJobExecutionStartedDomainEventHandler : IDomainEventHandle if (insertExecutionResult.IsFailure) throw new EventualConsistencyException(insertExecutionResult.FirstError, insertExecutionResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); // Notify the SignalR clients about the current scheduled jobs and the started execution. await NotifyCurrentScheduledJobsAsync(cancellationToken).ConfigureAwait(false); await _scheduledJobNotifier.SendScheduledJobExecutionStartedAsync(execution.ToResponse(), cancellationToken).ConfigureAwait(false); } - /// - /// Creates a copy of with the provided status and timestamps. - /// - /// The scheduled job to copy. - /// The status of the copy. - /// The last start time of the copy. - /// The last completion time of the copy. - /// The copy of the scheduled job. - private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) - { - return new ScheduledJobEntity - { - Id = scheduledJob.Id, - Name = scheduledJob.Name, - TaskType = scheduledJob.TaskType, - ScheduleType = scheduledJob.ScheduleType, - IntervalMinutes = scheduledJob.IntervalMinutes, - Hour = scheduledJob.Hour, - Minute = scheduledJob.Minute, - Status = status, - OwnerUserId = scheduledJob.OwnerUserId, - LastStartedOnUtc = lastStartedOnUtc, - LastCompletedOnUtc = lastCompletedOnUtc, - CreatedOnUtc = scheduledJob.CreatedOnUtc, - CreatedBy = scheduledJob.CreatedBy, - UpdatedOnUtc = scheduledJob.UpdatedOnUtc, - UpdatedBy = scheduledJob.UpdatedBy - }; - } - /// /// Notifies the SignalR clients about the current list of scheduled jobs. /// /// Cancellation token that can be used to stop the execution. private async Task NotifyCurrentScheduledJobsAsync(CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs index cc735453..3e98c4a5 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -50,31 +52,20 @@ public class ScheduledJobExecutionStoppedDomainEventHandler : IDomainEventHandle if (getOpenExecutionResult.Value is not null) { ScheduledJobExecutionEntity execution = getOpenExecutionResult.Value; - ScheduledJobExecutionEntity updatedExecution = new() - { - Id = execution.Id, - ScheduledJobId = execution.ScheduledJobId, - TaskType = execution.TaskType, - IsCycleRun = execution.IsCycleRun, - WasCycleActive = execution.WasCycleActive, - StartedOnUtc = execution.StartedOnUtc, - CompletedOnUtc = domainEvent.OccurredOnUtc, - CreatedOnUtc = execution.CreatedOnUtc, - CreatedBy = execution.CreatedBy, - UpdatedOnUtc = execution.UpdatedOnUtc, - UpdatedBy = execution.UpdatedBy - }; + ScheduledJobExecutionEntity updatedExecution = execution.ToUpdatedRepositoryEntity(domainEvent.OccurredOnUtc); Result updateExecutionResult = await _unitOfWork.ScheduledJobExecutionRepository.UpdateAsync(updatedExecution, cancellationToken).ConfigureAwait(false); if (updateExecutionResult.IsFailure) throw new EventualConsistencyException(updateExecutionResult.FirstError, updateExecutionResult.Errors); - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new EventualConsistencyException(saveChangesResult.FirstError, saveChangesResult.Errors); } // Notify the SignalR clients about the current list of scheduled jobs. - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs index 892a64f4..ac537d3e 100644 --- a/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandler.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.Mapping.Scheduling; using Lumina.Application.Core.Scheduling.Notifications; using Lumina.Contracts.Responses.Scheduling; @@ -42,10 +44,10 @@ public class ScheduledJobRemovedDomainEventHandler : IDomainEventHandlerCancellation token that can be used to stop the execution. public async ValueTask HandleAsync(ScheduledJobRemovedDomainEvent domainEvent, CancellationToken cancellationToken) { - Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) throw new EventualConsistencyException(getScheduledJobsResult.FirstError, getScheduledJobsResult.Errors); - IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())]; + IReadOnlyList scheduledJobResponses = [.. getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())]; await _scheduledJobNotifier.SendScheduledJobsAsync(scheduledJobResponses, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs index 9991ac07..112a8666 100644 --- a/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs +++ b/src/Lumina.Application/Core/Scheduling/Queries/GetScheduledJobs/GetScheduledJobsQueryHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; 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.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Mapping.Scheduling; @@ -63,10 +65,10 @@ public class GetScheduledJobsQueryHandler : IQueryHandler> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getScheduledJobsResult = await _unitOfWork.ScheduledJobRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobsResult.IsFailure) return getScheduledJobsResult.Errors; - return Result.From(getScheduledJobsResult.Value.Select(scheduledJob => scheduledJob.ToResponse())); + return Result.From(getScheduledJobsResult.Value.Data.Select(scheduledJob => scheduledJob.ToResponse())); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs index ec859146..99517c85 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/DeleteTheme/DeleteThemeCommandHandler.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Themes; @@ -71,7 +73,7 @@ public class DeleteThemeCommandHandler : ICommandHandler> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getAllResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getAllResult.IsFailure) return getAllResult.Errors; - List availableThemes = getAllResult.Value.Where(availableTheme => !availableTheme.IsDeleted).ToList(); + List availableThemes = getAllResult.Value.Data.Where(availableTheme => !availableTheme.IsDeleted).ToList(); - // at least one bundled theme must always remain available, so the application never ends up without any theme + // At least one bundled theme must always remain available, so the application never ends up without any theme. if (theme.InstallSource == ThemeInstallSource.Bundled) { int availableBundledThemes = availableThemes.Count(availableTheme => availableTheme.InstallSource == ThemeInstallSource.Bundled); @@ -97,7 +99,7 @@ public class DeleteThemeCommandHandler : ICommandHandler deleteResult = await _unitOfWork.ThemeRepository.DeleteByIdAsync(theme.Id, cancellationToken).ConfigureAwait(false); if (deleteResult.IsFailure) return deleteResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; Result deleteFilesResult = await _themeService.DeleteAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); if (deleteFilesResult.IsFailure) diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs index e914fa89..1f9e1268 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandler.cs @@ -74,11 +74,11 @@ public class InstallThemeCommandHandler : ICommandHandler installResult = await _themeService.InstallAsync(command.Archive!, cancellationToken).ConfigureAwait(false); if (installResult.IsFailure) return installResult.Errors; @@ -103,7 +103,7 @@ public class InstallThemeCommandHandler : ICommandHandler insertResult = await _unitOfWork.ThemeRepository.InsertAsync(themeEntity, cancellationToken).ConfigureAwait(false); if (insertResult.IsFailure) { - // roll back the stored files so a failed install leaves no orphaned theme pack behind + // Roll back the stored files so a failed install leaves no orphaned theme pack behind. await _themeService.DeleteAsync(manifest.Id, cancellationToken).ConfigureAwait(false); return insertResult.Errors; } } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return themeEntity.ToResponse(); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs index c092f1ac..ec4b1a68 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandler.cs @@ -70,7 +70,7 @@ public class RestoreThemeCommandHandler : ICommandHandler restoreFilesResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false); if (restoreFilesResult.IsFailure) return restoreFilesResult.Errors; @@ -99,7 +99,9 @@ public class RestoreThemeCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Success; } diff --git a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs index 3269b174..0fa7bb67 100644 --- a/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandler.cs @@ -66,7 +66,7 @@ public class SetCurrentThemeCommandHandler : ICommandHandler getCurrentResult = await _unitOfWork.ThemeRepository.GetCurrentAsync(cancellationToken).ConfigureAwait(false); if (getCurrentResult.IsFailure) return getCurrentResult.Errors; @@ -92,12 +94,16 @@ public class SetCurrentThemeCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return theme.ToResponse(); } } diff --git a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs index 419d1d9a..57402dfb 100644 --- a/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs +++ b/src/Lumina.Application/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandler.cs @@ -58,6 +58,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler 0) return validationResult; + // Load the requested theme, so that a missing or soft deleted theme is reported before its template is read. Result getThemeResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(query.ThemeId!, cancellationToken).ConfigureAwait(false); if (getThemeResult.IsFailure) return getThemeResult.Errors; @@ -69,10 +70,10 @@ public class GetThemeTemplateQueryHandler : IQueryHandler templateResult = await _themeService.GetTemplateAsync(theme.ThemeId, query.PageKey!, cancellationToken).ConfigureAwait(false); if (templateResult.IsFailure) { - // the stored files of a bundled theme removed externally are restored, and if the broken theme was the + // The stored files of a bundled theme removed externally are restored, and if the broken theme was the // active one, the configured default theme is activated, so clients always have a renderable theme; a // theme that simply does not provide a template for the page is not broken, so it is not restored and the - // caller falls back to the application's default unstyled Razor view instead + // caller falls back to the application's default unstyled Razor view instead. if (templateResult.FirstError != DomainErrors.Themes.ThemeTemplateNotFound && theme.InstallSource == ThemeInstallSource.Bundled && await TryRestoreBundledThemeAsync(theme, cancellationToken).ConfigureAwait(false)) @@ -99,6 +100,7 @@ public class GetThemeTemplateQueryHandler : IQueryHandler getDefaultResult = await _unitOfWork.ThemeRepository.GetByThemeIdAsync(_themeService.DefaultThemeId, cancellationToken).ConfigureAwait(false); @@ -114,7 +116,10 @@ public class GetThemeTemplateQueryHandler : IQueryHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return false; } } @@ -126,8 +131,8 @@ public class GetThemeTemplateQueryHandler : IQueryHandler public async Task>> HandleAsync(GetThemesQuery query, CancellationToken cancellationToken) { - Result> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getThemesResult = await _unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getThemesResult.IsFailure) return getThemesResult.Errors; - // deleted bundled themes are returned as well, so the administration page can offer to restore them - return Result.From>([.. getThemesResult.Value + // Deleted bundled themes are returned as well, so the administration page can offer to restore them. + return Result.From>([.. getThemesResult.Value.Data .OrderBy(theme => theme.IsDeleted) - // the shipped bundled themes are listed before the user themes, so the defaults stay the most visible + // The shipped bundled themes are listed before the user themes, so the defaults stay the most visible. .ThenByDescending(theme => theme.InstallSource == ThemeInstallSource.Bundled) .ThenBy(theme => theme.Name, StringComparer.OrdinalIgnoreCase) .Select(theme => theme.ToResponse())]); diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs index 1f5d127a..33e8dde6 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/ChangePassword/ChangePasswordCommandHandler.cs @@ -55,23 +55,32 @@ public class ChangePasswordCommandHandler : ICommandHandler 0) return validationResult; + // Load the account by its username, so the current password can be verified before it is replaced. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - // validate if the current password is correct + + // Validate that the provided current password matches the stored hash, so a request with only a valid username cannot overwrite the password. if (!_hashService.CheckStringAgainstHash(command.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!))) return Errors.Authentication.InvalidCurrentPassword; + + // The stored hash is URI escaped, so the new hash is escaped the same way before it is stored. getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(command.NewPassword!)); - // if the password change was initiated via a password reset, remote the temporary password that was generated in the process + + // If the password change was initiated via a password reset, remove the temporary password that was generated in the process. getUserResult.Value.TempPassword = null; getUserResult.Value.TempPasswordCreated = null; - // update the user + + // Update the user and persist the change. Result updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); if (updateUserResult.IsFailure) return updateUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return new ChangePasswordResponse(true); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs index e97e1704..28c7d4ca 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RecoverPassword/RecoverPasswordCommandHandler.cs @@ -64,31 +64,37 @@ public class RecoverPasswordCommandHandler : ICommandHandler 0) return validationResult; - // check if any users already exists + // Load the account by its username, so its existing recovery state and TOTP configuration can be checked. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; - else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested + else if (getUserResult.Value.TempPassword is not null) // If a temporary password is present, a password reset was already requested. return Errors.Authentication.PasswordResetAlreadyRequested; - // check if the user uses TOTP - bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret); - if (!usesTotp) + + // Check if the user uses TOTP. + bool doesUseTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret); + if (!doesUseTotp) return Errors.Authentication.InvalidTotpCode; - if (usesTotp && string.IsNullOrEmpty(command.TotpCode)) + if (doesUseTotp && string.IsNullOrEmpty(command.TotpCode)) return Errors.Authentication.InvalidTotpCode; - else if (usesTotp && !string.IsNullOrEmpty(command.TotpCode)) // and if they do, validate it + else if (doesUseTotp && !string.IsNullOrEmpty(command.TotpCode)) // When the user uses TOTP, validate the provided code before allowing the reset. if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), command.TotpCode)) return Errors.Authentication.InvalidTotpCode; - // hash the new password and assign it to a temporary password that will be valid 15 minutes - getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator + + // Generate the hash of a temporary password and record when it was created, so that the reset flow can expire it after 15 minutes. + getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: Replace the hardcoded password with a randomly generated one. getUserResult.Value.TempPasswordCreated = DateTime.UtcNow; - // update the user + + // Update the user and persist the temporary password. Result updateUserResult = await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false); if (updateUserResult.IsFailure) return updateUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return new RecoverPasswordResponse(true); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs index 7777826d..6f5b83b6 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandler.cs @@ -73,12 +73,14 @@ public class RegisterUserCommandHandler : ICommandHandler 0) return validationResult; - // check if any users already exists (admin account is only set once!) + // Check if a user with this username already exists, since the admin account can only be created once. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(command.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is not null) return Errors.Authentication.UsernameAlreadyExists; + + // Build the account, hashing the password and URI escaping it the same way as the stored form. string? totpSecret = null; Guid id = Guid.NewGuid(); UserEntity user = new() @@ -93,23 +95,29 @@ public class RegisterUserCommandHandler : ICommandHandler insertUserResult = await _unitOfWork.UserRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false); if (insertUserResult.IsFailure) return insertUserResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - // TODO: insert the default admin profile preferences when they are implemented - // if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // TODO: Insert the default admin profile preferences when they are implemented. + // If 2FA was enabled, the TOTP secret needs to be delivered to the client unencrypted, so it can be displayed. return new RegistrationResponse(user.Id, user.Username, totpSecret); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs index f6381a4c..1797831b 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/GetUsers/GetUsersQueryHandler.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -50,17 +52,17 @@ public class GetUsersQueryHandler : IQueryHandler public async Task>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken) { - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can see the list of users + // Only admins can see the list of users. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - Result> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); - return getRolesResult.Match(value => Result.From(value.ToResponses()), errors => errors); + Result> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); + return getRolesResult.Match(value => Result.From(value.Data.ToResponses()), errors => errors); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs index 919a348d..1b0910ee 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authentication/Queries/LoginUser/LoginUserQueryHandler.cs @@ -73,28 +73,31 @@ public class LoginUserQueryHandler : IQueryHandler 0) return validationResult; - // check if any users already exists + // Load the account by its username, so the password and two factor state can be verified. Result getUserResult = await _unitOfWork.UserRepository.GetByUsernameAsync(query.Username!, cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.InvalidUsernameOrPassword; - // validate that the password is correct + + // Validate that the password matches the stored hash. if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!))) { - // if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too + // If a password reset was requested, a temporary password is in use; when the check against the regular password failed, try the temporary one too. if (getUserResult.Value.TempPassword is not null) { - // the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error + // The temporary password is only valid for 15 minutes; when it is obsolete, remove it and return an error. if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow) { getUserResult.Value.TempPassword = null; getUserResult.Value.TempPasswordCreated = null; await _unitOfWork.UserRepository.UpdateAsync(getUserResult.Value, cancellationToken); - await _unitOfWork.SaveChangesAsync(cancellationToken); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Errors.Authentication.TempPasswordExpired; } - else // temporary password is still valid, validate password against it + else // The temporary password is still valid, so validate the password against it. { if (!_hashService.CheckStringAgainstHash(query.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!))) return Errors.Authentication.InvalidUsernameOrPassword; @@ -103,15 +106,17 @@ public class LoginUserQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return ApplicationErrors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can update user authorizations + // Only admins can update user authorizations. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return ApplicationErrors.Authorization.NotAuthorized; - // get the user to update - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken).ConfigureAwait(false); + // Get the user to update. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(command.UserId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return DomainErrors.Users.UserDoesNotExist; - Result getRoleResult = default; + RoleEntity? newRole = null; if (command.RoleId is not null) { - // get the new role - getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken).ConfigureAwait(false); + // Get the new role. + Result getRoleResult = await _unitOfWork.RoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getRoleResult.IsFailure || getRoleResult.Value is null) return ApplicationErrors.Authorization.RoleNotFound; + newRole = getRoleResult.Value; - // check if we're changing an admin's role and if this would leave us without admins - if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin") + // Check if changing the role of an admin would leave the application without any admin. + if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && newRole.RoleName != "Admin") { - // count how many admins we have - Result> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + // Count how many admins exist, so the last one is never demoted. + Result> getAllUsersResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getAllUsersResult.IsFailure) return getAllUsersResult.Errors; - int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin"); + int adminCount = getAllUsersResult.Value.Data.Count(user => user.UserRole?.Role.RoleName == "Admin"); if (adminCount <= 1) return ApplicationErrors.Authorization.CannotRemoveLastAdmin; } } - // get the permissions to assign + + // Get the permissions to assign. Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetByIdsAsync(command.Permissions, cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; - // update the user + // Every requested permission must exist, otherwise the requested permission set cannot be built and an unknown Id would throw instead of returning a result. + Dictionary permissionsById = getPermissionsResult.Value.ToDictionary(permission => permission.Id); + if (command.Permissions.Any(permissionId => !permissionsById.ContainsKey(permissionId))) + return ApplicationErrors.Authorization.PermissionNotFound; + + // Update the user. UserEntity userToUpdate = getUserResult.Value; - UserRoleEntity? userRole = default!; - if (command.RoleId is not null) - { - userRole = new() + // Build the role link for the requested role, keeping the current role untouched when no role was provided. + UserRoleEntity? userRole = command.RoleId is null + ? userToUpdate.UserRole + : new UserRoleEntity { UserId = userToUpdate.Id, RoleId = command.RoleId.Value, - Role = getRoleResult.Value!, + Role = newRole!, User = userToUpdate }; - } - + + // Build the updated user by copying the unchanged fields and replacing the role and permissions with the requested ones. UserEntity updatedUser = new() { Id = userToUpdate.Id, @@ -132,22 +141,24 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler permission.Id == permissionId), + Permission = permissionsById[permissionId], User = userToUpdate })], LibraryScans = userToUpdate.LibraryScans }; - // save changes and return result + // Save the changes and return the result. Result updateResult = await _unitOfWork.UserRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return new AuthorizationResponse( userToUpdate.Id, - getRoleResult.Value?.RoleName, + newRole?.RoleName ?? userToUpdate.UserRole?.Role.RoleName, userToUpdate.UserPermissions .Select(up => up.Permission.PermissionName) .ToHashSet() diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs index 54acf7b6..ae8e36e1 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandler.cs @@ -58,22 +58,25 @@ public class GetUserPermissionsQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can see the list of authorization permissions + // Only admins can see the list of authorization permissions. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // get the user from the repository and return its permissions - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + + // Get the user from the repository, so that a missing user is reported before its permissions are mapped. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; + + // Return the permissions of the user, mapped to their response representations. return Result.From(getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission).ToResponses()); } } diff --git a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs index 5b876904..fea42fc4 100644 --- a/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandler.cs @@ -57,22 +57,25 @@ public class GetUserRoleQueryHandler : IQueryHandler 0) return validationResult; - // an authenticated request must always carry a user identity + // An authenticated request must always carry a user identity. Guid? currentUserId = _currentUserService.UserId; if (currentUserId is null) return Errors.Authorization.NotAuthorized; Guid userId = currentUserId.Value; - // only admins can see the authorization role + // Only admins can see the authorization role. bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false); if (!isAdmin) return Errors.Authorization.NotAuthorized; - // get the user from the repository and return its roles - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken).ConfigureAwait(false); + + // Get the user from the repository, so that a missing user is reported before its role is mapped. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; else if (getUserResult.Value is null) return Errors.Authentication.UsernameDoesNotExist; + + // Return the role of the user, or null when the user has no role assigned. return Result.From(getUserResult.Value.UserRole?.Role.ToResponse()); } } 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 8b7bf775..af92e828 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -106,7 +106,10 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + return Result.Updated; } } diff --git a/src/Lumina.Contracts/DTO/Common/MoodDto.cs b/src/Lumina.Contracts/DTO/Common/MoodDto.cs new file mode 100644 index 00000000..5e0379ad --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/MoodDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.Common; + +/// +/// Data transfer object for a mood of a media element. +/// +/// The name of the mood. +[DebuggerDisplay("Name: {Name}")] +public record MoodDto( + string? Name +); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs index 4ba7a284..20efbdd4 100644 --- a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorDto.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System.Diagnostics; #endregion @@ -8,9 +9,9 @@ namespace Lumina.Contracts.DTO.MediaContributors; /// Data transfer object for a media contributor. /// /// The name details of the media contributor, including display and legal names. -/// The role details of the media contributor, including the role name and category. +/// The canonical role of the media contributor in the media item, used as the key of its localized display string. [DebuggerDisplay("Name: {Name}, Role: {Role}")] public record MediaContributorDto( MediaContributorNameDto? Name, - MediaContributorRoleDto? Role + MediaContributorRole? Role ); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorReferenceDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorReferenceDto.cs new file mode 100644 index 00000000..ea48d8c7 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorReferenceDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaContributors; + +/// +/// Data transfer object for the reference to a media contributor in a media item, carrying the role the contributor played. +/// +/// The unique identifier of the media contributor. +/// The role the contributor played. +[DebuggerDisplay("{ContributorId} - {Role}")] +public record MediaContributorReferenceDto( + Guid ContributorId, + MediaContributorRole Role +); diff --git a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs b/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs deleted file mode 100644 index d9265dda..00000000 --- a/src/Lumina.Contracts/DTO/MediaContributors/MediaContributorRoleDto.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.DTO.MediaContributors; - -/// -/// Data transfer object for the role of a media contributor in a media item. -/// -/// The display name of the role assigned to the media contributor. -/// The canonical category of the role. -[DebuggerDisplay("Name: {Name}, Category: {Category}")] -public record MediaContributorRoleDto( - string? Name, - MediaContributorRoleCategory? Category -); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/AudioRatingDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/AudioRatingDto.cs new file mode 100644 index 00000000..967eb530 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/AudioRatingDto.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; + +/// +/// Data transfer object for the rating of an audio media element. +/// +/// The rating value of the audio media element. +/// The maximum possible rating value of the audio media element. +/// The source of the audio rating (e.g., a specific website or platform). +/// The number of votes that contributed to the audio rating. +[DebuggerDisplay("{Value}/{MaxValue}")] +public record AudioRatingDto( + decimal? Value, + decimal? MaxValue, + AudioRatingSource? Source, + int? VoteCount +) : RatingDto(Value, MaxValue, VoteCount); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs new file mode 100644 index 00000000..3510ef65 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs @@ -0,0 +1,40 @@ +#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 an album. +/// +/// 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 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 status of the release. Optional. +/// The number of discs of the release. Optional. +/// The number of tracks of the release. Required. +[DebuggerDisplay("Title: {Title}")] +public record AlbumMetadataDto( + string? Title, + string? OriginalTitle, + string? Description, + ReleaseInfoDto? ReleaseInfo, + LanguageInfoDto? Language, + LanguageInfoDto? OriginalLanguage, + List? Tags, + List? Genres, + MusicReleaseType? ReleaseType, + MusicReleaseStatus? ReleaseStatus, + int? TotalDiscs, + int? TotalTracks +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs new file mode 100644 index 00000000..5fa4deee --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs @@ -0,0 +1,43 @@ +#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 the audio metadata of a track. +/// +/// 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 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 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. +[DebuggerDisplay("Title: {Title}")] +public record AudioMetadataDto( + string? Title, + string? OriginalTitle, + string? Description, + ReleaseInfoDto? ReleaseInfo, + LanguageInfoDto? Language, + LanguageInfoDto? OriginalLanguage, + List? Tags, + List? Genres, + int? DurationInSeconds, + int? SampleRate, + int? Channels, + int? BitDepth, + string? AudioCodec, + int? Bitrate +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/IsrcDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/IsrcDto.cs new file mode 100644 index 00000000..a11ef413 --- /dev/null +++ b/src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/IsrcDto.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; + +/// +/// Data transfer object for an ISRC (International Standard Recording Code) of a track. +/// +/// The value of the ISRC. +[DebuggerDisplay("Value: {Value}")] +public record IsrcDto( + string? Value +); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs index 7bcff9cb..c51d9910 100644 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs @@ -9,9 +9,9 @@ namespace Lumina.Contracts.Requests.FileSystemManagement.Directories; /// Represents a request to get the directories of a file system path. /// /// The file system path for which to get the directories. Required. -/// Whether to include hidden file system elements or not. Optional. +/// Whether to include hidden file system elements or not. Optional. [DebuggerDisplay("Path: {Path}")] public record GetDirectoriesRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs index e751efc9..87b8412e 100644 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetFilesRequest.cs @@ -9,9 +9,9 @@ namespace Lumina.Contracts.Requests.FileSystemManagement.Files; /// Represents a request to get the files at a file system path. /// /// The file system path for which to get the files. Required. -/// Whether to include hidden file system elements or not. Optional. +/// Whether to include hidden file system elements or not. Optional. [DebuggerDisplay("Path: {Path}")] public record GetFilesRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs index a5660c6f..53fc694e 100644 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs @@ -9,9 +9,9 @@ namespace Lumina.Contracts.Requests.FileSystemManagement.Files; /// Represents a request to get the files of a file system path. /// /// The file system path for which to get the tree files. Required. -/// Whether to include hidden file system elements or not. Optional. +/// Whether to include hidden file system elements or not. Optional. [DebuggerDisplay("Path: {Path}")] public record GetTreeFilesRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs index 16990e50..845d011d 100644 --- a/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs +++ b/src/Lumina.Contracts/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs @@ -9,9 +9,9 @@ namespace Lumina.Contracts.Requests.FileSystemManagement.Path; /// Represents a request to check the existence of a file system path. /// /// The file system path to check the exitence of. Required. -/// Whether to include hidden elements in the search results, or not. Optional. -[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] +/// Whether to include hidden elements in the search results, or not. Optional. +[DebuggerDisplay("Path: {Path}, ShouldIncludeHiddenElements: {ShouldIncludeHiddenElements}")] public record CheckPathExistsRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs new file mode 100644 index 00000000..e082c21a --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs @@ -0,0 +1,40 @@ +#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.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a request to add an album to an artist, together with the tracks of the album. +/// +/// The album metadata of the album. Required. +/// The physical or digital medium of the album. Optional. +/// The barcode of the album. Optional. +/// The catalog 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. Required. +/// The list of ratings for this album. Required. +/// The list of tracks of the album. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record AddAlbumRequest( + AlbumMetadataDto? Metadata, + MusicMediaFormat? MediaFormat, + string? Barcode, + string? CatalogNumber, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + List? Contributors, + List? Ratings, + List? Tracks +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequest.cs new file mode 100644 index 00000000..0f97b4ad --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a request to get the lightweight read models of the tracks of an album. +/// +/// The page of results to retrieve. Optional. +/// The maximum number of tracks to retrieve per page. Optional. +[DebuggerDisplay("CurrentPage: {CurrentPage}, PerPage: {PerPage}")] +public record GetAlbumTracksLiteRequest( + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs new file mode 100644 index 00000000..c7c95a70 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs @@ -0,0 +1,37 @@ +#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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a request to update an existing album. +/// +/// The album metadata of the album. Required. +/// The physical or digital medium of the album. Optional. +/// The barcode of the album. Optional. +/// The catalog 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. Required. +/// The list of ratings for this album. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateAlbumRequest( + AlbumMetadataDto? Metadata, + MusicMediaFormat? MediaFormat, + string? Barcode, + string? CatalogNumber, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + List? Contributors, + List? Ratings +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs new file mode 100644 index 00000000..53d76617 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// 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 website of the artist. Optional. +/// The MusicBrainz identifier of the artist. Optional. +/// The list of media contributors that make up the artist. Required. +/// The list of albums of the artist, each with its own list of tracks. Required. +[DebuggerDisplay("Name: {Name}")] +public record AddArtistRequest( + string? Name, + string? Website, + Guid? MusicBrainzArtistId, + List? Contributors, + List? Albums +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequest.cs new file mode 100644 index 00000000..0a6cc235 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to get the lightweight read models of the albums of an artist. +/// +/// The page of results to retrieve. Optional. +/// The maximum number of albums to retrieve per page. Optional. +[DebuggerDisplay("CurrentPage: {CurrentPage}, PerPage: {PerPage}")] +public record GetArtistAlbumsLiteRequest( + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequest.cs new file mode 100644 index 00000000..c4ff7444 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to get the lightweight read models of the artists of a media library. +/// +/// The page of results to retrieve. Optional. +/// The maximum number of artists to retrieve per page. Optional. +/// The search term used to filter the artists by name. Optional. +[DebuggerDisplay("SearchTerm: {SearchTerm}")] +public record GetArtistsLiteRequest( + int? CurrentPage, + int? PerPage, + string? SearchTerm +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequest.cs new file mode 100644 index 00000000..97028014 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to get the artists of a media library. +/// +/// The page of results to retrieve. Optional. +/// The maximum number of artists to retrieve per page. Optional. +/// The search term used to filter the artists by name. Optional. +[DebuggerDisplay("SearchTerm: {SearchTerm}")] +public record GetArtistsRequest( + int? CurrentPage, + int? PerPage, + string? SearchTerm +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs new file mode 100644 index 00000000..8e3b02ba --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequest.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to update an album of an artist, together with the tracks of the album, within an artist update. +/// +/// 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 barcode of the album. Optional. +/// The catalog 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. Required. +/// The list of ratings for this album. Required. +/// The list of tracks of the album, each with the Id of the track when the track already exists. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateArtistAlbumRequest( + Guid? AlbumId, + AlbumMetadataDto? Metadata, + MusicMediaFormat? MediaFormat, + string? Barcode, + string? CatalogNumber, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + List? Contributors, + List? Ratings, + List? Tracks +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs new file mode 100644 index 00000000..a300c302 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to update an existing artist. +/// +/// The name of the artist. Required. +/// The website of the artist. Optional. +/// The MusicBrainz identifier of the artist. Optional. +/// The list of media contributors that make up the artist. Required. +/// The list of albums of the artist, each with its own list of tracks. Required. +[DebuggerDisplay("Name: {Name}")] +public record UpdateArtistRequest( + string? Name, + string? Website, + Guid? MusicBrainzArtistId, + List? Contributors, + 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 new file mode 100644 index 00000000..2b7a10a2 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequest.cs @@ -0,0 +1,51 @@ +#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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to update a track of an album of an artist, within an artist update. +/// +/// The Id of the track, when the track already exists. Optional. +/// The file system path of the track. Required. +/// The audio metadata of the track. Required. +/// The number of the track on its disc. Required. +/// The number of the disc the track belongs to. 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 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. +/// The list of ratings for this track. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateArtistTrackRequest( + Guid? TrackId, + string? Path, + AudioMetadataDto? Metadata, + int? TrackNumber, + int? DiscNumber, + string? Script, + MusicKey? Key, + int? Bpm, + string? Work, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + Guid? MusicBrainzWorkId, + List? Moods, + List? Isrcs, + List? Contributors, + List? Ratings +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs new file mode 100644 index 00000000..6652f6a5 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs @@ -0,0 +1,49 @@ +#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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to add a track to an album. +/// +/// The file system path of the track. Required. +/// The audio metadata of the track. Required. +/// The number of the track on its disc. Required. +/// The number of the disc the track belongs to. 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 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. +/// The list of ratings for this track. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record AddTrackRequest( + string? Path, + AudioMetadataDto? Metadata, + int? TrackNumber, + int? DiscNumber, + string? Script, + MusicKey? Key, + int? Bpm, + string? Work, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + Guid? MusicBrainzWorkId, + List? Moods, + List? Isrcs, + List? Contributors, + List? Ratings +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs new file mode 100644 index 00000000..3a65a285 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs @@ -0,0 +1,49 @@ +#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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to update an existing track. +/// +/// The file system path of the track. Required. +/// The audio metadata of the track. Required. +/// The number of the track on its disc. Required. +/// The number of the disc the track belongs to. 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 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. +/// The list of ratings for this track. Required. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record UpdateTrackRequest( + string? Path, + AudioMetadataDto? Metadata, + int? TrackNumber, + int? DiscNumber, + string? Script, + MusicKey? Key, + int? Bpm, + string? Work, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + Guid? MusicBrainzWorkId, + List? Moods, + List? Isrcs, + List? Contributors, + List? Ratings +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs index 7754e087..0de7c352 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -13,8 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to add a book. /// -/// The Id of the media library this book belongs to. Required. -/// The file system path of the book. Required. +/// The file system path of the book. It must be inside one of the content locations of the media library that owns it. Required. /// Written content metadata of the book. Required. /// The format of the book (e.g., Hardcover, Paperback). Optional. /// The edition of the book. Optional. @@ -30,12 +29,11 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// The Barnes & Noble Id of the book. Optional. /// The Apple Books Id of the book. Optional. /// The list of ISBN (International Standard Book Number) of the book. Required. -/// The list of media contributors (actors, directors, etc) starring in this book. Required. +/// The list of media contributors of the book. Required. /// The list of ratings for this book. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record AddBookRequest( - Guid LibraryId, - string Path, + string? Path, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, @@ -51,6 +49,6 @@ public record AddBookRequest( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs deleted file mode 100644 index 3503cd03..00000000 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Represents a request to get a book by the specified Id. -/// -/// The unique identifier of the book to retrieve. -[DebuggerDisplay("Id: {Id}")] -public record GetBookRequest( - string? Id -); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs index 03b500ac..a49e34f4 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Diagnostics; #endregion @@ -9,7 +8,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to get the lightweight details of the books of a media library. /// -/// The Id of the media library whose books are retrieved. Required. /// The page of results to retrieve. Optional. /// The maximum number of books to retrieve per page. Optional. /// The search term used to filter results. Optional. @@ -21,9 +19,8 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// The name of the field by which to sort the results. Optional. /// The direction in which to sort the results. Optional. -[DebuggerDisplay("LibraryId: {LibraryId}")] +[DebuggerDisplay("SearchTerm: {SearchTerm}")] public record GetBooksLiteRequest( - Guid LibraryId, int? CurrentPage, int? PerPage, string? SearchTerm, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs index 257a402b..d23a3a14 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequest.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Diagnostics; #endregion @@ -9,15 +8,13 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to get the books of a media library. /// -/// The Id of the media library whose books are retrieved. Required. /// The page of results to retrieve. Optional. /// The maximum number of books to retrieve per page. Optional. /// The search term used to filter results. Optional. /// The name of the field by which to sort the results. Optional. /// The direction in which to sort the results. Optional. -[DebuggerDisplay("LibraryId: {LibraryId}")] +[DebuggerDisplay("SearchTerm: {SearchTerm}")] public record GetBooksRequest( - Guid LibraryId, int? CurrentPage, int? PerPage, string? SearchTerm, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs deleted file mode 100644 index 9dff87d4..00000000 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Represents a request to check the reading availability of a book. -/// -/// The Id of the book whose reading availability is checked. Required. -[DebuggerDisplay("BookId: {BookId}")] -public sealed record GetReadingAvailabilityRequest( - Guid BookId -); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs deleted file mode 100644 index abcf6fd3..00000000 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs +++ /dev/null @@ -1,15 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Represents a request to get the reading manifest of a book. -/// -/// The Id of the book whose reading manifest is retrieved. Required. -[DebuggerDisplay("BookId: {BookId}")] -public sealed record GetReadingManifestRequest( - Guid BookId -); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs deleted file mode 100644 index 6d82017d..00000000 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Represents a request to get a resource of a book, for reading. -/// -/// The Id of the book whose resource is retrieved. Required. -/// The opaque resource key of the resource. Required. -[DebuggerDisplay("BookId: {BookId}, ResourceKey: {ResourceKey}")] -public sealed record GetReadingResourceRequest( - Guid BookId, - string ResourceKey -); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs deleted file mode 100644 index aef859de..00000000 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Diagnostics; -#endregion - -namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Represents a request to get the content of a reading section of a book. -/// -/// The Id of the book whose reading section is retrieved. Required. -/// The opaque location reference of the reading section. Required. -[DebuggerDisplay("BookId: {BookId}, LocationRef: {LocationRef}")] -public sealed record GetReadingSectionRequest( - Guid BookId, - string LocationRef -); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs index 192ed038..4abc5ed9 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -12,7 +12,6 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// /// Represents a request to update an existing book. /// -/// The Id of the book to update, taken from the route. Required. /// Written content metadata of the book. Required. /// The format of the book (e.g., Hardcover, Paperback). Optional. /// The edition of the book. Optional. @@ -28,11 +27,10 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// The Barnes & Noble Id of the book. Optional. /// The Apple Books Id of the book. Optional. /// The list of ISBN (International Standard Book Number) of the book. Required. -/// The list of media contributors (actors, directors, etc) starring in this book. Required. +/// The list of media contributors of the book. Required. /// The list of ratings for this book. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record UpdateBookRequest( - string? Id, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, @@ -48,6 +46,6 @@ public record UpdateBookRequest( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponse.cs new file mode 100644 index 00000000..ac6aa364 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a lightweight album response, containing only the fields needed by the client for card-style navigation. +/// +/// The Id of the album. +/// The title of the album. +/// The number of tracks of the release. +[DebuggerDisplay("Title: {Title}")] +public record AlbumLiteResponse( + Guid Id, + string Title, + int TotalTracks +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs new file mode 100644 index 00000000..e71a8bef --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs @@ -0,0 +1,49 @@ +#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.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents an album response. +/// +/// The Id of the album. +/// The Id of the artist the album belongs to. +/// 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 barcode of the album, if applicable. +/// The catalog 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 date and time when the album was created. +/// The optional date and time when the album was updated. +/// The list of references to the media contributors that performed on the album, each with the role they played. +/// The list of ratings for this album. +/// The list of tracks of the album. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record AlbumResponse( + Guid Id, + Guid ArtistId, + Guid LibraryId, + AlbumMetadataDto Metadata, + MusicMediaFormat? MediaFormat, + string? Barcode, + string? CatalogNumber, + Guid? MusicBrainzReleaseId, + Guid? MusicBrainzReleaseGroupId, + Guid? MusicBrainzReleaseArtistId, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc, + List? Contributors, + List? Ratings, + List? Tracks +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponse.cs new file mode 100644 index 00000000..aa4b7faf --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponse.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a lightweight artist response, containing only the fields needed by the client for card-style navigation. +/// +/// The Id of the artist. +/// The name of the artist. +[DebuggerDisplay("Name: {Name}")] +public record ArtistLiteResponse( + Guid Id, + string Name +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs new file mode 100644 index 00000000..6cd9d3d0 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents an artist response. +/// +/// The Id of the artist. +/// The Id of the media library this artist belongs to. +/// The name 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 date and time when the artist was created. +/// The optional date and time when the artist was updated. +[DebuggerDisplay("Name: {Name}")] +public record ArtistResponse( + Guid Id, + Guid LibraryId, + string Name, + string? Website, + Guid? MusicBrainzArtistId, + List? Contributors, + List? Albums, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponse.cs new file mode 100644 index 00000000..263b3669 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a lightweight track response, containing only the fields needed by the client to display the tracks of an album. +/// +/// The Id of the track. +/// The title of the track. +/// The number of the track on its disc. +/// The number of the disc the track belongs to, if applicable. +[DebuggerDisplay("Title: {Title}")] +public record TrackLiteResponse( + Guid Id, + string Title, + int TrackNumber, + int? DiscNumber +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs new file mode 100644 index 00000000..72fd1ddb --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs @@ -0,0 +1,59 @@ +#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 System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a track response. +/// +/// The Id of the track. +/// The Id of the album the track belongs to. +/// The Id of the media library this track belongs to. +/// The file system path of the track. +/// The audio metadata of the track. +/// The number of the track on its disc. +/// The number of the disc the track belongs to, if applicable. +/// 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 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. +/// The list of ISRC (International Standard Recording Code) of the track. +/// The list of references to the media contributors that performed on the track, each with the role they played. +/// The list of ratings for this track. +[DebuggerDisplay("Title: {Metadata.Title}")] +public record TrackResponse( + Guid Id, + Guid AlbumId, + Guid LibraryId, + string Path, + AudioMetadataDto Metadata, + int TrackNumber, + int? DiscNumber, + string? Script, + MusicKey? Key, + int? Bpm, + string? Work, + Guid? MusicBrainzRecordingId, + Guid? MusicBrainzTrackId, + Guid? MusicBrainzWorkId, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc, + List? Moods, + List? Isrcs, + List? Contributors, + List? Ratings +); 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 bf4ea18d..97d9a8e3 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -31,7 +31,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr /// The Barnes & Noble ID of the book, if applicable. /// The Apple Books ID of the book, if applicable. /// The list of ISBN (International Standard Book Number) of the book. -/// The list of media contributors (actors, directors, etc) starring in this book. +/// The list of references to the media contributors that contributed to this book, each with the role they played. /// The list of ratings for this book. /// The status of the metadata enrichment of the book. /// The date and time when the metadata of the book was last enriched, if applicable. @@ -59,7 +59,7 @@ public record BookResponse( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings, MetadataStatus MetadataStatus, DateTime? LastMetadataUpdateUtc, diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponse.cs new file mode 100644 index 00000000..7432c840 --- /dev/null +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponse.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Represents the response of an update book cover operation. +/// +/// The relative path of the stored cover image. +[DebuggerDisplay("CoverPath: {CoverPath}")] +public record UpdateBookCoverResponse( + string CoverPath +); diff --git a/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs new file mode 100644 index 00000000..dcfc6aa0 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class AlbumConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Albums"); + builder.HasKey(album => album.Id); + builder.Property(album => album.Id) + .ValueGeneratedNever() + .HasColumnOrder(0); + + builder.Property(album => album.ArtistId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(album => album.LibraryId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(album => album.Title) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(3); + builder.Property(album => album.OriginalTitle) + .HasMaxLength(255) + .HasColumnOrder(4); + builder.Property(album => album.Description) + .HasMaxLength(2000) + .HasColumnOrder(5); + builder.Property(album => album.OriginalReleaseDate) + .HasColumnOrder(6); + builder.Property(album => album.OriginalReleaseYear) + .HasColumnOrder(7); + builder.Property(album => album.ReReleaseDate) + .HasColumnOrder(8); + builder.Property(album => album.ReReleaseYear) + .HasColumnOrder(9); + builder.Property(album => album.ReleaseCountry) + .HasConversion() + .HasMaxLength(2) + .HasColumnOrder(10); + builder.Property(album => album.ReleaseVersion) + .HasColumnOrder(11); + builder.Property(album => album.LanguageCode) + .HasColumnOrder(12); + builder.Property(album => album.LanguageName) + .HasColumnOrder(13); + builder.Property(album => album.LanguageNativeName) + .HasColumnOrder(14); + builder.Property(album => album.OriginalLanguageCode) + .HasColumnOrder(15); + builder.Property(album => album.OriginalLanguageName) + .HasColumnOrder(16); + builder.Property(album => album.OriginalLanguageNativeName) + .HasColumnOrder(17); + builder.Property(album => album.ReleaseType) + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(18); + builder.Property(album => album.ReleaseStatus) + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(19); + builder.Property(album => album.TotalDiscs) + .HasColumnOrder(20); + builder.Property(album => album.TotalTracks) + .HasColumnOrder(21); + builder.Property(album => album.MediaFormat) + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(22); + builder.Property(album => album.Barcode) + .HasMaxLength(13) + .HasColumnOrder(23); + builder.Property(album => album.CatalogNumber) + .HasMaxLength(50) + .HasColumnOrder(24); + builder.Property(album => album.MusicBrainzReleaseId) + .HasColumnOrder(25); + builder.Property(album => album.MusicBrainzReleaseGroupId) + .HasColumnOrder(26); + builder.Property(album => album.MusicBrainzReleaseArtistId) + .HasColumnOrder(27); + builder.Property(album => album.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(28); + builder.Property(album => album.CreatedBy) + .IsRequired() + .HasColumnOrder(29); + builder.Property(album => album.UpdatedOnUtc) + .HasColumnOrder(30); + builder.Property(album => album.UpdatedBy) + .HasColumnOrder(31); + + builder.HasOne(album => album.Artist) + .WithMany(artist => artist.Albums) + .HasForeignKey(album => album.ArtistId) + .OnDelete(DeleteBehavior.Cascade); + + // 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(album => album.Tags) + .WithMany() + .UsingEntity>( + "AlbumTags", + j => j.HasOne() + .WithMany() + .HasForeignKey("TagId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("AlbumId"), + j => + { + j.HasKey("AlbumId", "TagId"); + j.ToTable("AlbumTags"); + }); + + builder.HasMany(album => album.Genres) + .WithMany() + .UsingEntity>( + "AlbumGenres", + j => j.HasOne() + .WithMany() + .HasForeignKey("GenreId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("AlbumId"), + j => + { + j.HasKey("AlbumId", "GenreId"); + j.ToTable("AlbumGenres"); + }); + + builder.OwnsMany(album => album.Ratings, ratingBuilder => + { + ratingBuilder.ToTable("AlbumRatings"); + ratingBuilder.WithOwner() + .HasForeignKey("AlbumId"); + 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(album => album.Contributors) + .WithOne() + .HasForeignKey(contributor => contributor.AlbumId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasIndex(album => new { album.ArtistId, album.Title }); + builder.HasIndex(album => new { album.LibraryId, album.Title }); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/AlbumContributorConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/AlbumContributorConfiguration.cs new file mode 100644 index 00000000..01eb1bcf --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/AlbumContributorConfiguration.cs @@ -0,0 +1,57 @@ +#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 AlbumContributorConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("AlbumContributors"); + builder.HasKey(albumContributor => albumContributor.Id); + builder.Property(albumContributor => albumContributor.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(albumContributor => albumContributor.AlbumId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(albumContributor => albumContributor.MediaContributorId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(albumContributor => albumContributor.Role) + .HasConversion() + .HasMaxLength(50) + .IsRequired() + .HasColumnOrder(3); + + // audit + builder.Property(albumContributor => albumContributor.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(4); + + builder.Property(albumContributor => albumContributor.CreatedBy) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(albumContributor => albumContributor.UpdatedOnUtc) + .HasColumnOrder(6); + + builder.Property(albumContributor => albumContributor.UpdatedBy) + .HasColumnOrder(7); + + builder.HasIndex(albumContributor => new { albumContributor.AlbumId, albumContributor.MediaContributorId, albumContributor.Role }) + .IsUnique(); + builder.HasIndex(albumContributor => albumContributor.MediaContributorId); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs new file mode 100644 index 00000000..530f6917 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class ArtistConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Artists"); + builder.HasKey(artist => artist.Id); + builder.Property(artist => artist.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(artist => artist.LibraryId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(artist => artist.Name) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(2); + builder.Property(artist => artist.Website) + .HasMaxLength(2048) + .HasColumnOrder(3); + builder.Property(artist => artist.MusicBrainzArtistId) + .HasColumnOrder(4); + builder.Property(artist => artist.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + builder.Property(artist => artist.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + builder.Property(artist => artist.UpdatedOnUtc) + .HasColumnOrder(7); + builder.Property(artist => artist.UpdatedBy) + .HasColumnOrder(8); + + builder.HasMany(artist => artist.Contributors) + .WithOne() + .HasForeignKey(contributor => contributor.ArtistId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasIndex(artist => new { artist.LibraryId, artist.Name }) + .IsUnique(); // the same artist cannot appear twice in the same library + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/ArtistContributorConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/ArtistContributorConfiguration.cs new file mode 100644 index 00000000..b07ec32a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/ArtistContributorConfiguration.cs @@ -0,0 +1,57 @@ +#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 ArtistContributorConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("ArtistContributors"); + builder.HasKey(artistContributor => artistContributor.Id); + builder.Property(artistContributor => artistContributor.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(artistContributor => artistContributor.ArtistId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(artistContributor => artistContributor.MediaContributorId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(artistContributor => artistContributor.Role) + .HasConversion() + .HasMaxLength(50) + .IsRequired() + .HasColumnOrder(3); + + // audit + builder.Property(artistContributor => artistContributor.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(4); + + builder.Property(artistContributor => artistContributor.CreatedBy) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(artistContributor => artistContributor.UpdatedOnUtc) + .HasColumnOrder(6); + + builder.Property(artistContributor => artistContributor.UpdatedBy) + .HasColumnOrder(7); + + builder.HasIndex(artistContributor => new { artistContributor.ArtistId, artistContributor.MediaContributorId, artistContributor.Role }) + .IsUnique(); + builder.HasIndex(artistContributor => artistContributor.MediaContributorId); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs index cc710012..10031f61 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookConfiguration.cs @@ -149,17 +149,13 @@ public class BookConfiguration : IEntityTypeConfiguration builder.Property(book => book.MetadataProvider) .HasMaxLength(100) .HasColumnOrder(40); - builder.Property(book => book.CreatedOnUtc) - .HasColumnOrder(30); - builder.Property(book => book.UpdatedOnUtc) - .HasColumnOrder(31); - builder.HasMany(book => book.BookContributors) + builder.HasMany(book => book.Contributors) .WithOne() .HasForeignKey(bookContributor => bookContributor.BookId) .OnDelete(DeleteBehavior.Cascade); - builder.HasMany(book => book.BookArtwork) + builder.HasMany(book => book.Artwork) .WithOne() .HasForeignKey(bookArtwork => bookArtwork.BookId) .OnDelete(DeleteBehavior.Cascade); @@ -227,7 +223,8 @@ public class BookConfiguration : IEntityTypeConfiguration .HasDefaultValue(null) .HasColumnOrder(35); - builder.HasIndex(book => new { book.LibraryId, book.Path }); + builder.HasIndex(book => new { book.LibraryId, book.Path }) + .IsUnique(); // the same physical book on disk cannot appear twice in the same library builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus }); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs index dbc3ff30..62fa6705 100644 --- a/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/BookContributorConfiguration.cs @@ -1,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; #endregion @@ -22,40 +22,36 @@ public class BookContributorConfiguration : IEntityTypeConfiguration bookContributor.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(bookContributor => bookContributor.BookId) .IsRequired() .HasColumnOrder(1); builder.Property(bookContributor => bookContributor.MediaContributorId) .IsRequired() .HasColumnOrder(2); - builder.Property(bookContributor => bookContributor.RoleName) - .IsRequired() - .HasMaxLength(100) - .HasColumnOrder(3); - builder.Property(bookContributor => bookContributor.RoleCategory) - .IsRequired() + builder.Property(bookContributor => bookContributor.Role) .HasConversion() .HasMaxLength(50) - .HasColumnOrder(4); + .IsRequired() + .HasColumnOrder(3); // audit builder.Property(bookContributor => bookContributor.CreatedOnUtc) .IsRequired() - .HasColumnOrder(5); + .HasColumnOrder(4); builder.Property(bookContributor => bookContributor.CreatedBy) .IsRequired() - .HasColumnOrder(6); + .HasColumnOrder(5); builder.Property(bookContributor => bookContributor.UpdatedOnUtc) - .HasDefaultValue(null) - .HasColumnOrder(7); + .HasColumnOrder(6); builder.Property(bookContributor => bookContributor.UpdatedBy) - .HasDefaultValue(null) - .HasColumnOrder(8); + .HasColumnOrder(7); - builder.HasIndex(bookContributor => new { bookContributor.BookId, bookContributor.MediaContributorId }); + builder.HasIndex(bookContributor => new { bookContributor.BookId, bookContributor.MediaContributorId, bookContributor.Role }) + .IsUnique(); builder.HasIndex(bookContributor => bookContributor.MediaContributorId); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs new file mode 100644 index 00000000..c32b2194 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs @@ -0,0 +1,224 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class TrackConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Tracks"); + builder.HasKey(track => track.Id); + builder.Property(track => track.Id) + .ValueGeneratedNever() + .HasColumnOrder(0); + + builder.Property(track => track.AlbumId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(track => track.LibraryId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(track => track.Path) + .IsRequired() + .HasMaxLength(2048) + .HasColumnOrder(3); + builder.Property(track => track.Title) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(4); + builder.Property(track => track.OriginalTitle) + .HasMaxLength(255) + .HasColumnOrder(5); + builder.Property(track => track.Description) + .HasMaxLength(2000) + .HasColumnOrder(6); + builder.Property(track => track.OriginalReleaseDate) + .HasColumnOrder(7); + builder.Property(track => track.OriginalReleaseYear) + .HasColumnOrder(8); + builder.Property(track => track.ReReleaseDate) + .HasColumnOrder(9); + builder.Property(track => track.ReReleaseYear) + .HasColumnOrder(10); + builder.Property(track => track.ReleaseCountry) + .HasConversion() + .HasMaxLength(2) + .HasColumnOrder(11); + builder.Property(track => track.ReleaseVersion) + .HasColumnOrder(12); + builder.Property(track => track.LanguageCode) + .HasColumnOrder(13); + builder.Property(track => track.LanguageName) + .HasColumnOrder(14); + builder.Property(track => track.LanguageNativeName) + .HasColumnOrder(15); + builder.Property(track => track.OriginalLanguageCode) + .HasColumnOrder(16); + builder.Property(track => track.OriginalLanguageName) + .HasColumnOrder(17); + builder.Property(track => track.OriginalLanguageNativeName) + .HasColumnOrder(18); + builder.Property(track => track.DurationInSeconds) + .HasColumnOrder(19); + builder.Property(track => track.SampleRate) + .HasColumnOrder(20); + builder.Property(track => track.Channels) + .HasColumnOrder(21); + builder.Property(track => track.BitDepth) + .HasColumnOrder(22); + builder.Property(track => track.AudioCodec) + .HasMaxLength(50) + .HasColumnOrder(23); + builder.Property(track => track.Bitrate) + .HasColumnOrder(24); + builder.Property(track => track.TrackNumber) + .HasColumnOrder(25); + builder.Property(track => track.DiscNumber) + .HasColumnOrder(26); + builder.Property(track => track.Script) + .HasMaxLength(50) + .HasColumnOrder(27); + builder.Property(track => track.Key) + .HasConversion() + .HasMaxLength(50) + .HasColumnOrder(28); + builder.Property(track => track.Bpm) + .HasColumnOrder(29); + builder.Property(track => track.Work) + .HasMaxLength(255) + .HasColumnOrder(30); + builder.Property(track => track.MusicBrainzRecordingId) + .HasColumnOrder(31); + builder.Property(track => track.MusicBrainzTrackId) + .HasColumnOrder(32); + builder.Property(track => track.MusicBrainzWorkId) + .HasColumnOrder(33); + builder.Property(track => track.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(34); + builder.Property(track => track.CreatedBy) + .IsRequired() + .HasColumnOrder(35); + builder.Property(track => track.UpdatedOnUtc) + .HasColumnOrder(36); + builder.Property(track => track.UpdatedBy) + .HasColumnOrder(37); + + builder.HasOne(track => track.Album) + .WithMany(album => album.Tracks) + .HasForeignKey(track => track.AlbumId) + .OnDelete(DeleteBehavior.Cascade); + + // 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(track => track.Tags) + .WithMany() + .UsingEntity>( + "TrackTags", + j => j.HasOne() + .WithMany() + .HasForeignKey("TagId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("TrackId"), + j => + { + j.HasKey("TrackId", "TagId"); + j.ToTable("TrackTags"); + }); + + builder.HasMany(track => track.Genres) + .WithMany() + .UsingEntity>( + "TrackGenres", + j => j.HasOne() + .WithMany() + .HasForeignKey("GenreId"), + j => j.HasOne() + .WithMany() + .HasForeignKey("TrackId"), + j => + { + j.HasKey("TrackId", "GenreId"); + j.ToTable("TrackGenres"); + }); + + builder.OwnsMany(track => track.Moods, moodBuilder => + { + moodBuilder.ToTable("TrackMoods"); + moodBuilder.WithOwner() + .HasForeignKey("TrackId"); + moodBuilder.Property("Id") + .ValueGeneratedOnAdd(); + moodBuilder.HasKey("Id"); + + moodBuilder.Property(mood => mood.Name) + .IsRequired() + .HasMaxLength(50); + }); + + builder.OwnsMany(track => track.Isrcs, isrcBuilder => + { + isrcBuilder.ToTable("TrackIsrcs"); + isrcBuilder.WithOwner() + .HasForeignKey("TrackId"); + isrcBuilder.Property("Id") + .ValueGeneratedOnAdd(); + isrcBuilder.HasKey("Id"); + + isrcBuilder.Property(isrc => isrc.Value) + .HasColumnName("ISRC") + .HasMaxLength(12) + .IsRequired(); + }); + + builder.HasMany(track => track.Contributors) + .WithOne() + .HasForeignKey(contributor => contributor.TrackId) + .OnDelete(DeleteBehavior.Cascade); + + builder.OwnsMany(track => track.Ratings, ratingBuilder => + { + ratingBuilder.ToTable("TrackRatings"); + ratingBuilder.WithOwner() + .HasForeignKey("TrackId"); + 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.HasIndex(track => new { track.AlbumId, track.TrackNumber }); + builder.HasIndex(track => new { track.LibraryId, track.Path }) + .IsUnique(); // the same physical track file cannot appear twice in the same library + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackContributorConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackContributorConfiguration.cs new file mode 100644 index 00000000..6eada74d --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/TrackContributorConfiguration.cs @@ -0,0 +1,57 @@ +#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 TrackContributorConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("TrackContributors"); + builder.HasKey(trackContributor => trackContributor.Id); + builder.Property(trackContributor => trackContributor.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(trackContributor => trackContributor.TrackId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(trackContributor => trackContributor.MediaContributorId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(trackContributor => trackContributor.Role) + .HasConversion() + .HasMaxLength(50) + .IsRequired() + .HasColumnOrder(3); + + // audit + builder.Property(trackContributor => trackContributor.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(4); + + builder.Property(trackContributor => trackContributor.CreatedBy) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(trackContributor => trackContributor.UpdatedOnUtc) + .HasColumnOrder(6); + + builder.Property(trackContributor => trackContributor.UpdatedBy) + .HasColumnOrder(7); + + builder.HasIndex(trackContributor => new { trackContributor.TrackId, trackContributor.MediaContributorId, trackContributor.Role }) + .IsUnique(); + builder.HasIndex(trackContributor => trackContributor.MediaContributorId); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.Designer.cs new file mode 100644 index 00000000..c6bd79dc --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.Designer.cs @@ -0,0 +1,2606 @@ +// +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("20260910173956_AddsMusicLibraryAndCanonicalContributorRoles")] + partial class AddsMusicLibraryAndCanonicalContributorRoles + { + /// + 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("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("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("CatalogNumber") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name"); + + b.ToTable("Artists", (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("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + 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(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + 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("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("Work") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path"); + + 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"); + + 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("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("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.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.Navigation("Artist"); + + b.Navigation("Ratings"); + }); + + 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.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.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + }); + + 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("BookArtwork") + .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("BookContributors") + .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("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + 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/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs b/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs new file mode 100644 index 00000000..b87a0278 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs @@ -0,0 +1,680 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsMusicLibraryAndCanonicalContributorRoles : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_BookContributors_BookId_MediaContributorId", + table: "BookContributors"); + + migrationBuilder.DropColumn( + name: "RoleName", + table: "BookContributors"); + + migrationBuilder.RenameColumn( + name: "RoleCategory", + table: "BookContributors", + newName: "Role"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "BookContributors", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "BookContributors", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "BookContributors", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "BookContributors", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "Role", + table: "BookContributors", + type: "TEXT", + maxLength: 50, + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50) + .Annotation("Relational:ColumnOrder", 3) + .OldAnnotation("Relational:ColumnOrder", 4); + + migrationBuilder.CreateTable( + name: "Artists", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 255, nullable: false), + Website = table.Column(type: "TEXT", maxLength: 2048, nullable: true), + MusicBrainzArtistId = 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_Artists", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Albums", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + Title = table.Column(type: "TEXT", maxLength: 255, nullable: false), + OriginalTitle = table.Column(type: "TEXT", maxLength: 255, nullable: true), + Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + OriginalReleaseDate = table.Column(type: "TEXT", nullable: true), + OriginalReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReReleaseDate = table.Column(type: "TEXT", nullable: true), + ReReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReleaseCountry = table.Column(type: "TEXT", maxLength: 2, nullable: true), + ReleaseVersion = table.Column(type: "TEXT", nullable: true), + LanguageCode = table.Column(type: "TEXT", nullable: true), + LanguageName = table.Column(type: "TEXT", nullable: true), + LanguageNativeName = table.Column(type: "TEXT", nullable: true), + OriginalLanguageCode = table.Column(type: "TEXT", nullable: true), + OriginalLanguageName = table.Column(type: "TEXT", nullable: true), + OriginalLanguageNativeName = table.Column(type: "TEXT", nullable: true), + ReleaseType = table.Column(type: "TEXT", maxLength: 50, nullable: true), + ReleaseStatus = table.Column(type: "TEXT", maxLength: 50, nullable: true), + TotalDiscs = table.Column(type: "INTEGER", nullable: true), + TotalTracks = table.Column(type: "INTEGER", nullable: false), + MediaFormat = table.Column(type: "TEXT", maxLength: 50, nullable: true), + Barcode = table.Column(type: "TEXT", maxLength: 13, nullable: true), + CatalogNumber = table.Column(type: "TEXT", maxLength: 50, nullable: true), + MusicBrainzReleaseId = table.Column(type: "TEXT", nullable: true), + MusicBrainzReleaseGroupId = table.Column(type: "TEXT", nullable: true), + MusicBrainzReleaseArtistId = 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_Albums", x => x.Id); + table.ForeignKey( + name: "FK_Albums_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ArtistContributors", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ArtistId = table.Column(type: "TEXT", nullable: false), + MediaContributorId = table.Column(type: "TEXT", nullable: false), + Role = table.Column(type: "TEXT", maxLength: 50, nullable: false), + 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_ArtistContributors", x => x.Id); + table.ForeignKey( + name: "FK_ArtistContributors_Artists_ArtistId", + column: x => x.ArtistId, + principalTable: "Artists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AlbumContributors", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + AlbumId = table.Column(type: "TEXT", nullable: false), + MediaContributorId = table.Column(type: "TEXT", nullable: false), + Role = table.Column(type: "TEXT", maxLength: 50, nullable: false), + 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_AlbumContributors", x => x.Id); + table.ForeignKey( + name: "FK_AlbumContributors_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AlbumGenres", + columns: table => new + { + AlbumId = table.Column(type: "TEXT", nullable: false), + GenreId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AlbumGenres", x => new { x.AlbumId, x.GenreId }); + table.ForeignKey( + name: "FK_AlbumGenres_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AlbumGenres_Genres_GenreId", + column: x => x.GenreId, + principalTable: "Genres", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AlbumRatings", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Source = table.Column(type: "TEXT", maxLength: 50, nullable: true), + AlbumId = 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_AlbumRatings", x => x.Id); + table.ForeignKey( + name: "FK_AlbumRatings_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AlbumTags", + columns: table => new + { + AlbumId = table.Column(type: "TEXT", nullable: false), + TagId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AlbumTags", x => new { x.AlbumId, x.TagId }); + table.ForeignKey( + name: "FK_AlbumTags_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AlbumTags_Tags_TagId", + column: x => x.TagId, + principalTable: "Tags", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Tracks", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + AlbumId = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + Path = table.Column(type: "TEXT", maxLength: 2048, nullable: false), + Title = table.Column(type: "TEXT", maxLength: 255, nullable: false), + OriginalTitle = table.Column(type: "TEXT", maxLength: 255, nullable: true), + Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + OriginalReleaseDate = table.Column(type: "TEXT", nullable: true), + OriginalReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReReleaseDate = table.Column(type: "TEXT", nullable: true), + ReReleaseYear = table.Column(type: "INTEGER", nullable: true), + ReleaseCountry = table.Column(type: "TEXT", maxLength: 2, nullable: true), + ReleaseVersion = table.Column(type: "TEXT", nullable: true), + LanguageCode = table.Column(type: "TEXT", nullable: true), + LanguageName = table.Column(type: "TEXT", nullable: true), + LanguageNativeName = table.Column(type: "TEXT", nullable: true), + OriginalLanguageCode = table.Column(type: "TEXT", nullable: true), + OriginalLanguageName = table.Column(type: "TEXT", nullable: true), + OriginalLanguageNativeName = table.Column(type: "TEXT", 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), + TrackNumber = table.Column(type: "INTEGER", nullable: false), + DiscNumber = table.Column(type: "INTEGER", nullable: true), + Script = table.Column(type: "TEXT", maxLength: 50, nullable: true), + Key = table.Column(type: "TEXT", maxLength: 50, nullable: true), + Bpm = table.Column(type: "INTEGER", nullable: true), + Work = table.Column(type: "TEXT", maxLength: 255, nullable: true), + MusicBrainzRecordingId = table.Column(type: "TEXT", nullable: true), + MusicBrainzTrackId = table.Column(type: "TEXT", nullable: true), + MusicBrainzWorkId = 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_Tracks", x => x.Id); + table.ForeignKey( + name: "FK_Tracks_Albums_AlbumId", + column: x => x.AlbumId, + principalTable: "Albums", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackContributors", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + TrackId = table.Column(type: "TEXT", nullable: false), + MediaContributorId = table.Column(type: "TEXT", nullable: false), + Role = table.Column(type: "TEXT", maxLength: 50, nullable: false), + 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_TrackContributors", x => x.Id); + table.ForeignKey( + name: "FK_TrackContributors_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackGenres", + columns: table => new + { + TrackId = table.Column(type: "TEXT", nullable: false), + GenreId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TrackGenres", x => new { x.TrackId, x.GenreId }); + table.ForeignKey( + name: "FK_TrackGenres_Genres_GenreId", + column: x => x.GenreId, + principalTable: "Genres", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_TrackGenres_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackIsrcs", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + ISRC = table.Column(type: "TEXT", maxLength: 12, nullable: false), + TrackId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TrackIsrcs", x => x.Id); + table.ForeignKey( + name: "FK_TrackIsrcs_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackMoods", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 50, nullable: false), + TrackId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TrackMoods", x => x.Id); + table.ForeignKey( + name: "FK_TrackMoods_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackRatings", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Source = table.Column(type: "TEXT", maxLength: 50, nullable: true), + TrackId = 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_TrackRatings", x => x.Id); + table.ForeignKey( + name: "FK_TrackRatings_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "TrackTags", + columns: table => new + { + TrackId = table.Column(type: "TEXT", nullable: false), + TagId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_TrackTags", x => new { x.TrackId, x.TagId }); + table.ForeignKey( + name: "FK_TrackTags_Tags_TagId", + column: x => x.TagId, + principalTable: "Tags", + principalColumn: "Name", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_TrackTags_Tracks_TrackId", + column: x => x.TrackId, + principalTable: "Tracks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_BookContributors_BookId_MediaContributorId_Role", + table: "BookContributors", + columns: new[] { "BookId", "MediaContributorId", "Role" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AlbumContributors_AlbumId_MediaContributorId_Role", + table: "AlbumContributors", + columns: new[] { "AlbumId", "MediaContributorId", "Role" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AlbumContributors_MediaContributorId", + table: "AlbumContributors", + column: "MediaContributorId"); + + migrationBuilder.CreateIndex( + name: "IX_AlbumGenres_GenreId", + table: "AlbumGenres", + column: "GenreId"); + + migrationBuilder.CreateIndex( + name: "IX_AlbumRatings_AlbumId", + table: "AlbumRatings", + column: "AlbumId"); + + migrationBuilder.CreateIndex( + name: "IX_Albums_ArtistId_Title", + table: "Albums", + columns: new[] { "ArtistId", "Title" }); + + migrationBuilder.CreateIndex( + name: "IX_Albums_LibraryId_Title", + table: "Albums", + columns: new[] { "LibraryId", "Title" }); + + migrationBuilder.CreateIndex( + name: "IX_AlbumTags_TagId", + table: "AlbumTags", + column: "TagId"); + + migrationBuilder.CreateIndex( + name: "IX_ArtistContributors_ArtistId_MediaContributorId_Role", + table: "ArtistContributors", + columns: new[] { "ArtistId", "MediaContributorId", "Role" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ArtistContributors_MediaContributorId", + table: "ArtistContributors", + column: "MediaContributorId"); + + migrationBuilder.CreateIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists", + columns: new[] { "LibraryId", "Name" }); + + migrationBuilder.CreateIndex( + name: "IX_TrackContributors_MediaContributorId", + table: "TrackContributors", + column: "MediaContributorId"); + + migrationBuilder.CreateIndex( + name: "IX_TrackContributors_TrackId_MediaContributorId_Role", + table: "TrackContributors", + columns: new[] { "TrackId", "MediaContributorId", "Role" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_TrackGenres_GenreId", + table: "TrackGenres", + column: "GenreId"); + + migrationBuilder.CreateIndex( + name: "IX_TrackIsrcs_TrackId", + table: "TrackIsrcs", + column: "TrackId"); + + migrationBuilder.CreateIndex( + name: "IX_TrackMoods_TrackId", + table: "TrackMoods", + column: "TrackId"); + + migrationBuilder.CreateIndex( + name: "IX_TrackRatings_TrackId", + table: "TrackRatings", + column: "TrackId"); + + migrationBuilder.CreateIndex( + name: "IX_Tracks_AlbumId_TrackNumber", + table: "Tracks", + columns: new[] { "AlbumId", "TrackNumber" }); + + migrationBuilder.CreateIndex( + name: "IX_Tracks_LibraryId_Path", + table: "Tracks", + columns: new[] { "LibraryId", "Path" }); + + migrationBuilder.CreateIndex( + name: "IX_TrackTags_TagId", + table: "TrackTags", + column: "TagId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AlbumContributors"); + + migrationBuilder.DropTable( + name: "AlbumGenres"); + + migrationBuilder.DropTable( + name: "AlbumRatings"); + + migrationBuilder.DropTable( + name: "AlbumTags"); + + migrationBuilder.DropTable( + name: "ArtistContributors"); + + migrationBuilder.DropTable( + name: "TrackContributors"); + + migrationBuilder.DropTable( + name: "TrackGenres"); + + migrationBuilder.DropTable( + name: "TrackIsrcs"); + + migrationBuilder.DropTable( + name: "TrackMoods"); + + migrationBuilder.DropTable( + name: "TrackRatings"); + + migrationBuilder.DropTable( + name: "TrackTags"); + + migrationBuilder.DropTable( + name: "Tracks"); + + migrationBuilder.DropTable( + name: "Albums"); + + migrationBuilder.DropTable( + name: "Artists"); + + migrationBuilder.DropIndex( + name: "IX_BookContributors_BookId_MediaContributorId_Role", + table: "BookContributors"); + + migrationBuilder.RenameColumn( + name: "Role", + table: "BookContributors", + newName: "RoleCategory"); + + migrationBuilder.AlterColumn( + name: "UpdatedOnUtc", + table: "BookContributors", + type: "TEXT", + nullable: true, + oldClrType: typeof(DateTime), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 7) + .OldAnnotation("Relational:ColumnOrder", 6); + + migrationBuilder.AlterColumn( + name: "UpdatedBy", + table: "BookContributors", + type: "TEXT", + nullable: true, + oldClrType: typeof(Guid), + oldType: "TEXT", + oldNullable: true) + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 7); + + migrationBuilder.AlterColumn( + name: "CreatedOnUtc", + table: "BookContributors", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 5) + .OldAnnotation("Relational:ColumnOrder", 4); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "BookContributors", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 6) + .OldAnnotation("Relational:ColumnOrder", 5); + + migrationBuilder.AlterColumn( + name: "RoleCategory", + table: "BookContributors", + type: "TEXT", + maxLength: 50, + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 50) + .Annotation("Relational:ColumnOrder", 4) + .OldAnnotation("Relational:ColumnOrder", 3); + + migrationBuilder.AddColumn( + name: "RoleName", + table: "BookContributors", + type: "TEXT", + maxLength: 100, + nullable: false, + defaultValue: "") + .Annotation("Relational:ColumnOrder", 3); + + migrationBuilder.CreateIndex( + name: "IX_BookContributors_BookId_MediaContributorId", + table: "BookContributors", + columns: new[] { "BookId", "MediaContributorId" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260912151008_AddsUniqueBookLibraryIdPathIndex.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260912151008_AddsUniqueBookLibraryIdPathIndex.Designer.cs new file mode 100644 index 00000000..c9819419 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260912151008_AddsUniqueBookLibraryIdPathIndex.Designer.cs @@ -0,0 +1,2607 @@ +// +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("20260912151008_AddsUniqueBookLibraryIdPathIndex")] + partial class AddsUniqueBookLibraryIdPathIndex + { + /// + 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("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("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("CatalogNumber") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name"); + + b.ToTable("Artists", (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("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + 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(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + 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("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("Work") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path"); + + 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("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("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.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.Navigation("Artist"); + + b.Navigation("Ratings"); + }); + + 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.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.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + }); + + 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("BookArtwork") + .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("BookContributors") + .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("BookArtwork"); + + b.Navigation("BookContributors"); + }); + + 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/20260912151008_AddsUniqueBookLibraryIdPathIndex.cs b/src/Lumina.DataAccess/Common/Migrations/20260912151008_AddsUniqueBookLibraryIdPathIndex.cs new file mode 100644 index 00000000..018c5f46 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260912151008_AddsUniqueBookLibraryIdPathIndex.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsUniqueBookLibraryIdPathIndex : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Books_LibraryId_Path", + table: "Books"); + + migrationBuilder.CreateIndex( + name: "IX_Books_LibraryId_Path", + table: "Books", + columns: new[] { "LibraryId", "Path" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Books_LibraryId_Path", + table: "Books"); + + migrationBuilder.CreateIndex( + name: "IX_Books_LibraryId_Path", + table: "Books", + columns: new[] { "LibraryId", "Path" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260914175859_MakesArtistNameUniquePerLibrary.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260914175859_MakesArtistNameUniquePerLibrary.Designer.cs new file mode 100644 index 00000000..ab87466a --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260914175859_MakesArtistNameUniquePerLibrary.Designer.cs @@ -0,0 +1,2608 @@ +// +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("20260914175859_MakesArtistNameUniquePerLibrary")] + partial class MakesArtistNameUniquePerLibrary + { + /// + 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("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("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("CatalogNumber") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (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("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + 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(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + 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("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("Work") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path"); + + 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("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("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.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.Navigation("Artist"); + + b.Navigation("Ratings"); + }); + + 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.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.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + }); + + 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/20260914175859_MakesArtistNameUniquePerLibrary.cs b/src/Lumina.DataAccess/Common/Migrations/20260914175859_MakesArtistNameUniquePerLibrary.cs new file mode 100644 index 00000000..57cab478 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260914175859_MakesArtistNameUniquePerLibrary.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class MakesArtistNameUniquePerLibrary : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists"); + + migrationBuilder.CreateIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists", + columns: new[] { "LibraryId", "Name" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists"); + + migrationBuilder.CreateIndex( + name: "IX_Artists_LibraryId_Name", + table: "Artists", + columns: new[] { "LibraryId", "Name" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260916184415_MakesTrackPathUniquePerLibrary.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260916184415_MakesTrackPathUniquePerLibrary.Designer.cs new file mode 100644 index 00000000..2dc48eb0 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260916184415_MakesTrackPathUniquePerLibrary.Designer.cs @@ -0,0 +1,2609 @@ +// +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("20260916184415_MakesTrackPathUniquePerLibrary")] + partial class MakesTrackPathUniquePerLibrary + { + /// + 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("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("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("CatalogNumber") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (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("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + 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(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + 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("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("Work") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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("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("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.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.Navigation("Artist"); + + b.Navigation("Ratings"); + }); + + 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.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.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + }); + + 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/20260916184415_MakesTrackPathUniquePerLibrary.cs b/src/Lumina.DataAccess/Common/Migrations/20260916184415_MakesTrackPathUniquePerLibrary.cs new file mode 100644 index 00000000..d2d45098 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260916184415_MakesTrackPathUniquePerLibrary.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class MakesTrackPathUniquePerLibrary : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Tracks_LibraryId_Path", + table: "Tracks"); + + migrationBuilder.CreateIndex( + name: "IX_Tracks_LibraryId_Path", + table: "Tracks", + columns: new[] { "LibraryId", "Path" }, + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Tracks_LibraryId_Path", + table: "Tracks"); + + migrationBuilder.CreateIndex( + name: "IX_Tracks_LibraryId_Path", + table: "Tracks", + columns: new[] { "LibraryId", "Path" }); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 33199a11..0d628bfb 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -17,6 +17,36 @@ namespace Lumina.DataAccess.Common.Migrations #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("BookGenres", b => { b.Property("BookId") @@ -239,57 +269,6 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Tags", (string)null); }); - modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => - { - b.Property("Id") - .HasColumnType("TEXT") - .HasColumnOrder(0); - - b.Property("BookId") - .HasColumnType("TEXT") - .HasColumnOrder(1); - - b.Property("CreatedBy") - .HasColumnType("TEXT") - .HasColumnOrder(6); - - b.Property("CreatedOnUtc") - .HasColumnType("TEXT") - .HasColumnOrder(5); - - b.Property("MediaContributorId") - .HasColumnType("TEXT") - .HasColumnOrder(2); - - b.Property("RoleCategory") - .IsRequired() - .HasMaxLength(50) - .HasColumnType("TEXT") - .HasColumnOrder(4); - - b.Property("RoleName") - .IsRequired() - .HasMaxLength(100) - .HasColumnType("TEXT") - .HasColumnOrder(3); - - b.Property("UpdatedBy") - .HasColumnType("TEXT") - .HasColumnOrder(8); - - b.Property("UpdatedOnUtc") - .HasColumnType("TEXT") - .HasColumnOrder(7); - - b.HasKey("Id"); - - b.HasIndex("MediaContributorId"); - - b.HasIndex("BookId", "MediaContributorId"); - - b.ToTable("BookContributors", (string)null); - }); - modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => { b.Property("Id") @@ -345,6 +324,517 @@ namespace Lumina.DataAccess.Common.Migrations 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("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("CatalogNumber") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (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("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(24); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(29); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(19); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + 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(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + 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("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("Work") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(30); + + 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") @@ -701,6 +1191,52 @@ namespace Lumina.DataAccess.Common.Migrations 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") @@ -880,7 +1416,8 @@ namespace Lumina.DataAccess.Common.Migrations b.HasIndex("LibraryId", "MetadataStatus"); - b.HasIndex("LibraryId", "Path"); + b.HasIndex("LibraryId", "Path") + .IsUnique(); b.ToTable("Books", (string)null); }); @@ -1462,6 +1999,66 @@ namespace Lumina.DataAccess.Common.Migrations 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("BookGenres", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) @@ -1549,15 +2146,176 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("User"); }); - modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.BookContributorEntity", b => + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => { - b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) - .WithMany("BookContributors") - .HasForeignKey("BookId") + 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.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.Navigation("Artist"); + + b.Navigation("Ratings"); + }); + + 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.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.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) @@ -1658,7 +2416,16 @@ namespace Lumina.DataAccess.Common.Migrations 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("BookArtwork") + .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(); @@ -1743,6 +2510,36 @@ namespace Lumina.DataAccess.Common.Migrations .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"); @@ -1757,6 +2554,25 @@ namespace Lumina.DataAccess.Common.Migrations 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"); @@ -1769,9 +2585,9 @@ namespace Lumina.DataAccess.Common.Migrations modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => { - b.Navigation("BookArtwork"); + b.Navigation("Artwork"); - b.Navigation("BookContributors"); + b.Navigation("Contributors"); }); modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => diff --git a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs new file mode 100644 index 00000000..3fa99b6b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.Common.Persistence; + +/// +/// Reconciles the children of a tracked entity against a desired set, preserving the identity of the children that already exist. +/// +internal static class CollectionReconciler +{ + /// + /// Applies the desired onto the tracked , by matching both sides with the provided key selectors. + /// + /// + /// Existing items that are absent from the desired set are removed, desired items that are absent are added, and matched items are left untouched, unless + /// reports that their non-key values changed, in which case only that item is replaced. Because the tracked instances are + /// never rebuilt as a whole, the rows that did not change keep their identity and their audit columns. + /// + /// The type of the tracked items. + /// The type of the desired items. + /// The type of the key used to match the two sides. + /// The tracked collection that is reconciled in place. + /// The desired items. + /// Selects the matching key of a tracked item. + /// Selects the matching key of a desired item. + /// Determines whether a matched tracked item must be replaced, because a non-key value changed. + /// Creates the entity used for a desired item that is not matched by any tracked item. + public static void Reconcile( + ICollection existingItems, + IEnumerable incomingItems, + Func existingKeySelector, + Func incomingKeySelector, + Func shouldReplace, + Func createNew) + where TExisting : class + where TKey : notnull + { + // Index the tracked children by their key, so that each desired child can be matched in constant time; the first item wins when duplicate keys exist. + Dictionary existingByKey = []; + foreach (TExisting existingItem in existingItems) + existingByKey.TryAdd(existingKeySelector(existingItem), existingItem); + + // Materialize the desired children once, so the source is not enumerated repeatedly, and collect their keys for the removal pass. + List incomingList = [.. incomingItems]; + HashSet incomingKeys = [.. incomingList.Select(incomingKeySelector)]; + + // Remove the tracked children that are absent from the desired set, so that deletions are applied. + foreach (TExisting existingItem in existingItems.ToList()) + if (!incomingKeys.Contains(existingKeySelector(existingItem))) + existingItems.Remove(existingItem); + + // Reconcile each desired child, replacing a matched one only when its non-key values changed, so unchanged rows keep their identity and audit columns. + foreach (TIncoming incomingItem in incomingList) + { + TKey incomingKey = incomingKeySelector(incomingItem); + if (existingByKey.TryGetValue(incomingKey, out TExisting? matchedItem) && matchedItem is not null) + { + if (shouldReplace(matchedItem, incomingItem)) + { + TExisting replacementItem = createNew(incomingItem); + existingItems.Remove(matchedItem); + existingItems.Add(replacementItem); + existingByKey[incomingKey] = replacementItem; + } + } + else + { + // The desired child has no tracked counterpart, so it is added as a new child and indexed, so that a later desired child + // that reuses the same key is matched against it instead of adding a second row that would break the unique index. + TExisting addedItem = createNew(incomingItem); + existingItems.Add(addedItem); + existingByKey[incomingKey] = addedItem; + } + } + } +} diff --git a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs new file mode 100644 index 00000000..915e921b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.EntityFrameworkCore.Metadata; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.Common.Persistence; + +/// +/// Copies the editable scalar values of a mapped repository entity onto its tracked counterpart, while leaving the primary key and the audit columns under the sole ownership of the persistence medium. +/// +internal static class EditableValuesCopier +{ + /// + /// Copies the scalar values of onto the tracked entity, except for its primary key and its audit columns, + /// so that the tracked row is only considered modified when an editable value actually changed, and its stored identity is never reassigned. + /// + /// + /// The primary key is not copied, so that a mapped entity carrying a different, or unset, key can never retarget the tracked row. The audit interceptor stamps the + /// modification columns of the rows that are actually modified, so the audit columns are not copied either: copying them from the mapped entity would mark untouched + /// rows as modified, which would then be stamped with a change that the user never made. + /// + /// The type of the tracked and mapped repository entity. + /// The Entity Framework context that tracks . + /// The tracked entity whose editable values are updated. + /// The mapped entity carrying the desired values. + public static void CopyEditableValues(LuminaDbContext context, TEntity tracked, TEntity incoming) where TEntity : class, IAuditableEntity + { + EntityEntry trackedEntry = context.Entry(tracked); + EntityEntry incomingEntry = context.Entry(incoming); + + // The primary key and the audit columns are owned by the persistence medium, so they are never copied from the mapped entity. + HashSet excludedProperties = + [ + .. (trackedEntry.Metadata.FindPrimaryKey()?.Properties.Select(property => property.Name) ?? []), + nameof(IAuditableEntity.CreatedOnUtc), + nameof(IAuditableEntity.CreatedBy), + nameof(IAuditableEntity.UpdatedOnUtc), + nameof(IAuditableEntity.UpdatedBy) + ]; + + foreach (IProperty property in trackedEntry.Metadata.GetProperties()) + { + if (excludedProperties.Contains(property.Name)) + continue; + trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue; + } + } +} diff --git a/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs b/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs new file mode 100644 index 00000000..55d60ffa --- /dev/null +++ b/src/Lumina.DataAccess/Common/Persistence/SharedReferenceResolver.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +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.Common.Persistence; + +/// +/// Resolves shared reference rows, whose identity is their name, so that each distinct name is represented by a single tracked instance. +/// +/// +/// This is the toolkit's only concern expressed over a family of entity shapes, through the marker interface: +/// a shared reference is resolved by its name, the stored row wins over the incoming instance, and within-request duplicates are collapsed to one instance. +/// No per-entity method is ever needed, so a new shared reference type adds no new persistence type. A shared reference whose name is null or whitespace +/// cannot be keyed and would be lost silently, so it fails the resolution with the caller-provided error instead of being dropped. +/// +internal static class SharedReferenceResolver +{ + /// + /// Resolves the single instance that represents each distinct name carried by . + /// + /// + /// The stored row wins over the incoming instance, so that a shared reference that is already persisted is reused instead of inserted again. The + /// instances are also collapsed by name, so that a name shared by several parents of the same request is only ever tracked once. + /// + /// The type of the shared reference entity. + /// The Entity Framework context the stored rows are read through. + /// The shared references carried by the entity that is about to be persisted. + /// The error returned when a shared reference carries a name that is null or whitespace. + /// Cancellation token that can be used to stop the execution. + /// A result containing either a dictionary that maps each distinct name to the single instance that represents it, or an error. + internal static async Task>> ResolveAsync(LuminaDbContext context, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken) + where TEntity : class, ISharedReferenceEntity + { + // A shared reference whose name is null or whitespace cannot be keyed, and the database requires the name to be present, so the whole resolution + // fails instead of silently dropping the reference. + Dictionary resolvedByName = new(StringComparer.Ordinal); + foreach (TEntity incomingEntity in incomingEntities) + { + string? name = incomingEntity.Name; + if (string.IsNullOrWhiteSpace(name)) + return invalidNameError; + resolvedByName.TryAdd(name, incomingEntity); + } + + if (resolvedByName.Count == 0) + return resolvedByName; + + // Prefer the instances that the context already tracks, so that a reference resolved earlier in the same request does not trigger another query. + HashSet namesResolvedFromTrackedEntities = []; + foreach (TEntity trackedEntity in context.Set().Local) + { + string? trackedName = trackedEntity.Name; + if (!string.IsNullOrWhiteSpace(trackedName) && resolvedByName.ContainsKey(trackedName)) + { + resolvedByName[trackedName] = trackedEntity; + namesResolvedFromTrackedEntities.Add(trackedName); + } + } + + // Only the names that are not already tracked are read from the storage medium. + List unresolvedNames = [.. resolvedByName.Keys.Where(name => !namesResolvedFromTrackedEntities.Contains(name))]; + if (unresolvedNames.Count > 0) + { + List storedEntities = await context.Set() + .Where(entity => unresolvedNames.Contains(EF.Property(entity, nameof(ISharedReferenceEntity.Name)))) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + foreach (TEntity storedEntity in storedEntities) + resolvedByName[storedEntity.Name!] = storedEntity; + } + + return resolvedByName; + } + + /// + /// Maps to the single resolved instance that represents each of their names. + /// + /// The type of the shared reference entity. + /// The shared references that must be mapped to their resolved instances. + /// The resolved instances, as returned by . + /// The resolved instances, without any duplicate. + internal static IReadOnlyCollection Normalize(IEnumerable incomingEntities, IReadOnlyDictionary resolvedEntities) + where TEntity : class, ISharedReferenceEntity + { + HashSet normalizedEntities = []; + foreach (TEntity incomingEntity in incomingEntities) + { + string? name = incomingEntity.Name; + if (string.IsNullOrWhiteSpace(name)) + continue; + if (resolvedEntities.TryGetValue(name, out TEntity? resolvedEntity) && resolvedEntity is not null) + normalizedEntities.Add(resolvedEntity); + } + return normalizedEntities; + } + + /// + /// Reconciles the shared reference collection against , reusing the stored rows whose names already exist. + /// + /// The type of the shared reference entity. + /// The Entity Framework context the stored rows are read through. + /// The tracked collection that is reconciled in place. + /// The desired shared references. + /// The error returned when a shared reference carries a name that is null or whitespace. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + internal static async Task> ReconcileAsync(LuminaDbContext context, ICollection existingEntities, IEnumerable incomingEntities, Error invalidNameError, CancellationToken cancellationToken) + where TEntity : class, ISharedReferenceEntity + { + List incomingList = [.. incomingEntities]; + Result> resolveResult = await ResolveAsync(context, incomingList, invalidNameError, cancellationToken).ConfigureAwait(false); + if (resolveResult.IsFailure) + return resolveResult.Errors; + + CollectionReconciler.Reconcile( + existingEntities, + Normalize(incomingList, resolveResult.Value), + existingEntity => existingEntity.Name!, + incomingEntity => incomingEntity.Name!, + shouldReplace: (existingEntity, incomingEntity) => false, + createNew: incomingEntity => incomingEntity); + return Result.Updated; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs index 26a77760..72d5d6ab 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/PermissionRepository.cs @@ -2,8 +2,11 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -38,8 +41,8 @@ internal sealed class PermissionRepository : IPermissionRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(PermissionEntity permission, CancellationToken cancellationToken) { - bool permissionExists = await _luminaDbContext.Permissions.AnyAsync(repositoryPermission => repositoryPermission.Id == permission.Id, cancellationToken).ConfigureAwait(false); - if (permissionExists) + bool doesPermissionExist = await _luminaDbContext.Permissions.AnyAsync(repositoryPermission => repositoryPermission.Id == permission.Id, cancellationToken).ConfigureAwait(false); + if (doesPermissionExist) return Errors.Authorization.PermissionAlreadyExists; _luminaDbContext.Permissions.Add(permission); @@ -47,13 +50,54 @@ internal sealed class PermissionRepository : IPermissionRepository } /// - /// Gets all autorization permissions. + /// Gets all the authorization permissions, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching permissions are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.Permissions.ToListAsync(cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Permissions; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the permissions. + if (paginationData is null) + { + IReadOnlyList allPermissions = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allPermissions, + CurrentPage = 1, + PerPage = allPermissions.Count, + Count = allPermissions.Count, + NumberOfPages = 1 + }; + } + + int count = await query.Select(permission => permission.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs index cbf17889..83941416 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Authorization/RoleRepository.cs @@ -2,11 +2,16 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -37,8 +42,8 @@ internal sealed class RoleRepository : IRoleRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(RoleEntity role, CancellationToken cancellationToken) { - bool roleExists = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id || repositoryRole.RoleName == role.RoleName, cancellationToken).ConfigureAwait(false); - if (roleExists) + bool doesRoleExist = await _luminaDbContext.Roles.AnyAsync(repositoryRole => repositoryRole.Id == role.Id || repositoryRole.RoleName == role.RoleName, cancellationToken).ConfigureAwait(false); + if (doesRoleExist) return Errors.Authorization.RoleAlreadyExists; _luminaDbContext.Roles.Add(role); @@ -46,13 +51,57 @@ internal sealed class RoleRepository : IRoleRepository } /// - /// Gets all autorization roles. + /// Gets all the authorization roles, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching roles are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.Roles.ToListAsync(cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Roles; + // Apply no-tracking when the caller only reads, so the entities are not tracked by the context. + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the roles. + if (paginationData is null) + { + IReadOnlyList allRoles = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allRoles, + CurrentPage = 1, + PerPage = allRoles.Count, + Count = allRoles.Count, + NumberOfPages = 1 + }; + } + + // Count the matching roles first, so the requested page can be clamped to the number of available pages. + int count = await query.Select(role => role.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + // Fetch only the requested page of roles. + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -66,6 +115,7 @@ internal sealed class RoleRepository : IRoleRepository return await _luminaDbContext.Roles .Include(role => role.RolePermissions) .ThenInclude(library => library.Permission) + .AsSplitQuery() .FirstOrDefaultAsync(role => role.RoleName == roleType, cancellationToken) .ConfigureAwait(false); } @@ -76,13 +126,18 @@ internal sealed class RoleRepository : IRoleRepository /// The id of the authorization role to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.Roles - .Include(role => role.RolePermissions) - .ThenInclude(rolePermission => rolePermission.Permission) - .FirstOrDefaultAsync(role => role.Id == id, cancellationToken) - .ConfigureAwait(false); + IQueryable query = _luminaDbContext.Roles; + // Apply no-tracking when the caller only reads, so the entities are not tracked by the context. + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query + .Include(role => role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) + .AsSplitQuery(); + return await query.FirstOrDefaultAsync(role => role.Id == id, cancellationToken).ConfigureAwait(false); } /// @@ -93,19 +148,33 @@ internal sealed class RoleRepository : IRoleRepository /// An representing either a successful operation, or an error. public async Task> UpdateAsync(RoleEntity data, CancellationToken cancellationToken) { - // check if a role with the requested Id exists, and retrieve it + // Check if a role with the requested Id exists, and retrieve it. RoleEntity? foundRole = await _luminaDbContext.Roles .Include(role => role.RolePermissions) .ThenInclude(rolePermission => rolePermission.Permission) + .AsSplitQuery() .FirstOrDefaultAsync(role => role.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundRole is null) return Errors.Authorization.RoleNotFound; - // update scalar properties - _luminaDbContext.Entry(foundRole).CurrentValues.SetValues(data); - // update owned entities (their changes are not automatically tracked by EF) - foundRole.RolePermissions.Clear(); - foreach (RolePermissionEntity rolePermission in data.RolePermissions) - foundRole.RolePermissions.Add(rolePermission); + + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundRole, data); + + // A permission participation is matched by its permission. Matched participations keep their identity and their audit columns, so a permission + // that is referenced elsewhere is never deleted and re-inserted just because another field of the role was edited. + CollectionReconciler.Reconcile( + foundRole.RolePermissions, + data.RolePermissions, + existingRolePermission => existingRolePermission.PermissionId, + incomingRolePermission => incomingRolePermission.PermissionId, + shouldReplace: (existingRolePermission, incomingRolePermission) => false, + createNew: incomingRolePermission => new RolePermissionEntity + { + RoleId = foundRole.Id, + PermissionId = incomingRolePermission.PermissionId, + Permission = incomingRolePermission.Permission, + Role = foundRole + }); return Result.Updated; } @@ -117,12 +186,13 @@ internal sealed class RoleRepository : IRoleRepository /// An representing either a successful operation, or an error. public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) { - // check if a role with the requested Id exists, and retrieve it + // Check if a role with the requested Id exists, and retrieve it. RoleEntity? foundRole = await _luminaDbContext.Roles .FirstOrDefaultAsync(role => role.Id == id, cancellationToken).ConfigureAwait(false); if (foundRole is null) return Errors.Authorization.RoleNotFound; - // then, remove it + + // Remove the role. _luminaDbContext.Remove(foundRole); return Result.Deleted; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs similarity index 65% rename from src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs rename to src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index ecda2029..f0fca470 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -2,11 +2,13 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Specifications; -using Lumina.DataAccess.Core.Repositories.Books.Specifications; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -24,7 +26,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.Core.Repositories.Books; +namespace Lumina.DataAccess.Core.Repositories.BookLibrary; /// /// Repository for books. @@ -54,22 +56,25 @@ internal sealed class BookRepository : IBookRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(BookEntity book, CancellationToken cancellationToken) { - bool bookExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); - if (bookExists) + bool doesBookExist = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.Id == book.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesBookExist) return Errors.WrittenContent.BookAlreadyExists; - // Fetch existing tags and genres. - List existingTags = await _luminaDbContext.Set() - .Where(t => book.Tags.Select(bt => bt.Name).Contains(t.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); + // A book is unique within its library by its file system path, so the same file can never be registered twice in the same library. + bool doesBookPathExist = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.LibraryId == book.LibraryId && repositoryBook.Path == book.Path, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesBookPathExist) + return Errors.WrittenContent.BookAlreadyExists; - List existingGenres = await _luminaDbContext.Set() - .Where(g => book.Genres.Select(bg => bg.Name).Contains(g.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); + // Resolve the tags and genres of the book to a single instance per name, replacing the stored ones where they exist, so that the shared tables are not duplicated. + Result> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, book.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveTagsResult.IsFailure) + return resolveTagsResult.Errors; + Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, book.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveGenresResult.IsFailure) + return resolveGenresResult.Errors; - // Replace tags and genres in the book with existing ones. - book.Tags = [.. book.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; - book.Genres = [.. book.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; + book.Tags = [.. SharedReferenceResolver.Normalize(book.Tags, resolveTagsResult.Value)]; + book.Genres = [.. SharedReferenceResolver.Normalize(book.Genres, resolveGenresResult.Value)]; _luminaDbContext.Books.Add(book); return Result.Created; @@ -81,54 +86,53 @@ internal sealed class BookRepository : IBookRepository /// The Id of the book to get. /// Cancellation token that can be used to stop the execution. /// An containing either a , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.Books - .Include(book => book.Tags) - .Include(book => book.Genres) - .Include(book => book.ISBNs) - .Include(book => book.Ratings) - .Include(book => book.BookContributors) - .Include(book => book.BookArtwork) - .FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Books; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + query = query + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.Contributors) + .Include(book => book.Artwork) + .AsSplitQuery(); + } + return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); } /// - /// Gets all books. - /// - /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) - { - return await _luminaDbContext.Books - .Include(book => book.Tags) - .Include(book => book.Genres) - .Include(book => book.ISBNs) - .Include(book => book.Ratings) - .Include(book => book.BookContributors) - .Include(book => book.BookArtwork) - .ToListAsync(cancellationToken).ConfigureAwait(false); - } - - /// - /// Gets paginated books. + /// Gets paginated books, or all the books of the matching filters when the pagination data is . /// /// The type of the filter used for filtering the data. /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching books are returned. /// The name of the fields by which to sort the results. /// The direction in which to sort the results. /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. /// An containing either a , or an error. - public async Task>> GetPaginatedAsync(PaginationDataDto? paginationData, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - IQueryable booksQuery = _luminaDbContext.Books - .Include(book => book.Tags) - .Include(book => book.Genres) - .Include(book => book.ISBNs) - .Include(book => book.Ratings) - .Include(book => book.BookArtwork) - .AsNoTracking(); + IQueryable booksQuery = _luminaDbContext.Books; + if (!shouldTrackEntities) + booksQuery = booksQuery.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + booksQuery = booksQuery + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.Contributors) + .Include(book => book.Artwork) + .AsSplitQuery(); + } // Books should always be retrieved only per owning libraries. if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) @@ -178,6 +182,95 @@ internal sealed class BookRepository : IBookRepository }; } + /// + /// Gets paginated lightweight read models of the books of the media library identified by the provided , + /// or all of them when the pagination data is , projecting only the fields needed to display the books in a grid or a list. + /// + /// The type of the filter used for filtering the data. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching books are returned. + /// The name of the fields by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> GetAllLiteAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + { + // Books should always be retrieved only per owning libraries. + if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) + return Errors.Library.FilterMustIncludeLibraryId; + + // The lightweight read models are retrieved without tracking by default, because they are never modified by the caller. + IQueryable booksQuery = _luminaDbContext.Books; + if (!shouldTrackEntities) + booksQuery = booksQuery.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + booksQuery = booksQuery + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.Contributors) + .Include(book => book.Artwork) + .AsSplitQuery(); + } + + booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId); + + FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter); + if (filterSpecification is not null) + booksQuery = booksQuery.Where(filterSpecification.ToExpression()); + + // Apply sorting based on the specified sortBy and sortOrder parameters. + booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); + + IQueryable liteRowsQuery = booksQuery.Select(book => new BookLiteRow + { + Id = book.Id, + Title = book.Title, + ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear, + CoverPath = book.Artwork + .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) + .Select(artwork => artwork.FileName) + .FirstOrDefault() + }); + + // If no pagination was requested, return all the books of the library. + if (paginationData is null) + { + IReadOnlyList allBooks = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allBooks, + CurrentPage = 1, + PerPage = allBooks.Count, + Count = allBooks.Count, + NumberOfPages = 1 + }; + } + + int count = await booksQuery.Select(book => book.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + // Apply pagination. + IReadOnlyList paginatedResult = await liteRowsQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + /// /// Gets all the books of the media library identified by . /// @@ -190,7 +283,9 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) - .Include(book => book.BookArtwork) + .Include(book => book.Contributors) + .Include(book => book.Artwork) + .AsSplitQuery() .Where(book => book.LibraryId == libraryId) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -208,7 +303,8 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) - .Include(book => book.BookArtwork) + .Include(book => book.Artwork) + .AsSplitQuery() .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); } @@ -227,7 +323,8 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) - .Include(book => book.BookContributors) + .Include(book => book.Contributors) + .AsSplitQuery() .Where(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) @@ -263,9 +360,10 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) - .Include(book => book.BookArtwork) + .Include(book => book.Artwork) + .AsSplitQuery() .Where(book => book.LibraryId == libraryId - && !book.BookArtwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched) + && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched) && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) .OrderBy(book => book.Path) .Take(pageSize) @@ -282,7 +380,7 @@ internal sealed class BookRepository : IBookRepository { return await _luminaDbContext.Books .CountAsync(book => book.LibraryId == libraryId - && !book.BookArtwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken) + && !book.Artwork.Any(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Status == ArtworkStatus.Enriched), cancellationToken) .ConfigureAwait(false); } @@ -353,7 +451,7 @@ internal sealed class BookRepository : IBookRepository public async Task>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection bookIds, CancellationToken cancellationToken) { List authorRows = await _luminaDbContext.BookContributors - .Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.RoleCategory == MediaContributorRoleCategory.Author) + .Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.Role == MediaContributorRole.Author) .Join(_luminaDbContext.MediaContributors, bookContributor => bookContributor.MediaContributorId, contributor => contributor.Id, @@ -374,15 +472,15 @@ internal sealed class BookRepository : IBookRepository private sealed record AuthorRow(Guid BookId, string DisplayName); /// - /// Deletes the book identified by . + /// Deletes the book identified by . /// - /// The Id of the book to delete. + /// The Id 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> DeleteAsync(Guid bookId, CancellationToken cancellationToken) + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) { BookEntity? book = await _luminaDbContext.Books - .FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == bookId, cancellationToken).ConfigureAwait(false); + .FirstOrDefaultAsync(repositoryBook => repositoryBook.Id == id, cancellationToken).ConfigureAwait(false); if (book is null) return Errors.WrittenContent.BookNotFound; @@ -391,7 +489,7 @@ internal sealed class BookRepository : IBookRepository } /// - /// Updates a book, replacing its editable data while preserving its identity, enrichment and audit columns. + /// Updates a book, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, its enrichment columns and its audit columns. /// /// The book whose editable data is applied to the stored book. /// Cancellation token that can be used to stop the execution. @@ -403,50 +501,63 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) + .Include(book => book.Contributors) + .AsSplitQuery() .FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundBook is null) return Errors.WrittenContent.BookNotFound; - // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. + // The stored enrichment and identity columns are never overwritten by an edit: they are owned by the scan and by the record itself. The audit columns are + // only ever written by the auditing interceptor, which is why the copier restores them after copying the editable values. Guid libraryId = foundBook.LibraryId; string path = foundBook.Path; MetadataStatus metadataStatus = foundBook.MetadataStatus; DateTime? lastMetadataUpdateUtc = foundBook.LastMetadataUpdateUtc; string? metadataProvider = foundBook.MetadataProvider; - DateTime createdOnUtc = foundBook.CreatedOnUtc; - Guid createdBy = foundBook.CreatedBy; - - // Copy the editable scalar properties of the book, ignoring the unchanged collection and enrichment columns. - _luminaDbContext.Entry(foundBook).CurrentValues.SetValues(data); + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundBook, data); foundBook.LibraryId = libraryId; foundBook.Path = path; foundBook.MetadataStatus = metadataStatus; foundBook.LastMetadataUpdateUtc = lastMetadataUpdateUtc; foundBook.MetadataProvider = metadataProvider; - foundBook.CreatedOnUtc = createdOnUtc; - foundBook.CreatedBy = createdBy; - // Reuse the stored tags and genres whose names already exist, so that the shared tables are not duplicated. - List existingTags = await _luminaDbContext.Set() - .Where(tag => data.Tags.Select(bookTag => bookTag.Name).Contains(tag.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); - List existingGenres = await _luminaDbContext.Set() - .Where(genre => data.Genres.Select(bookGenre => bookGenre.Name).Contains(genre.Name)) - .ToListAsync(cancellationToken).ConfigureAwait(false); + // Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted. + Result reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundBook.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundBook.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileGenresResult.IsFailure) + return reconcileGenresResult.Errors; - foundBook.Tags.Clear(); - foundBook.Tags.UnionWith(data.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); - foundBook.Genres.Clear(); - foundBook.Genres.UnionWith(data.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + // ISBNs are owned value objects with no identity anyone could reference, so an ISBN whose format changed is replaced as a whole, while the ones that did not + // change are left exactly as they are stored. Matching by the ISBN value keeps an update in place instead of recreating every ISBN of the book. + CollectionReconciler.Reconcile( + foundBook.ISBNs, + data.ISBNs, + existingIsbn => existingIsbn.Value ?? string.Empty, + incomingIsbn => incomingIsbn.Value ?? string.Empty, + shouldReplace: (existingIsbn, incomingIsbn) => !existingIsbn.Equals(incomingIsbn), + createNew: incomingIsbn => incomingIsbn); - // Replace the owned collections of the book, so that removed entries are deleted and new entries are inserted. - foundBook.ISBNs.Clear(); - foundBook.ISBNs.AddRange(data.ISBNs); - foundBook.Ratings.Clear(); - foundBook.Ratings.AddRange(data.Ratings); - foundBook.BookContributors.Clear(); - foundBook.BookContributors.AddRange(data.BookContributors); + // Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change + // are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the book. + CollectionReconciler.Reconcile( + foundBook.Ratings, + data.Ratings, + existingRating => existingRating.Source?.ToString() ?? string.Empty, + incomingRating => incomingRating.Source?.ToString() ?? string.Empty, + shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating), + createNew: incomingRating => incomingRating); + + // A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a + // contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the book was edited. + CollectionReconciler.Reconcile( + foundBook.Contributors, + data.Contributors, + existingContributor => (existingContributor.MediaContributorId, existingContributor.Role), + incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role), + shouldReplace: (existingContributor, incomingContributor) => false, + createNew: incomingContributor => incomingContributor); return Result.Updated; } @@ -460,7 +571,7 @@ internal sealed class BookRepository : IBookRepository /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker) { - return sortBy?.ToLower() switch + return sortBy?.ToLowerInvariant() switch { "languagecode" => sortOrder == SortOrder.Descending ? booksQuery.OrderByDescending(book => book.LanguageCode) diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecification.cs similarity index 99% rename from src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs rename to src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecification.cs index 39731c29..790cd379 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecification.cs @@ -8,7 +8,7 @@ using System.Linq.Expressions; using System.Reflection; #endregion -namespace Lumina.DataAccess.Core.Repositories.Books.Specifications; +namespace Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; /// /// Represents a filter specification for filtering books by the alpha key of their title, for the alpha picker. diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookSearchSpecification.cs similarity index 55% rename from src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs rename to src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookSearchSpecification.cs index 18cb7e22..eb494292 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookSearchSpecification.cs @@ -5,7 +5,7 @@ using System; using System.Linq.Expressions; #endregion -namespace Lumina.DataAccess.Core.Repositories.Books.Specifications; +namespace Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; /// /// Represents a filter specification for filtering or searching book entities based on a search term. @@ -29,6 +29,14 @@ internal sealed class BookSearchSpecification : FilterSpecification /// An expression tree that can be used to evaluate whether a satisfies the specification criteria. public override Expression> ToExpression() { - return book => book.Title.Contains(_searchTerm) || (book.OriginalTitle != null && book.OriginalTitle.Contains(_searchTerm)); + // The term is normalized with the invariant culture, so that the case folding never depends on the current culture. The columns are + // folded by the storage medium, which keeps the search case-insensitive. + string normalizedSearchTerm = _searchTerm.ToLowerInvariant(); +#pragma warning disable IDE0079 // Remove unnecessary suppression. +#pragma warning disable CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string comparisons. This expression is translated to SQL; the StringComparison overloads are client-side only and are not translated, so they would fail at query time. + return book => book.Title.ToLower().Contains(normalizedSearchTerm) + || (book.OriginalTitle != null && book.OriginalTitle.ToLower().Contains(normalizedSearchTerm)); +#pragma warning restore CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string comparisons. +#pragma warning restore IDE0079 // Remove unnecessary suppression. } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs index 43b63d9e..c5168a61 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryRepository.cs @@ -2,8 +2,12 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -38,8 +42,8 @@ internal sealed class LibraryRepository : ILibraryRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(LibraryEntity library, CancellationToken cancellationToken) { - bool libraryExists = await _luminaDbContext.Libraries.AnyAsync(repositoryLibrary => repositoryLibrary.Id == library.Id, cancellationToken: cancellationToken).ConfigureAwait(false); - if (libraryExists) + bool doesLibraryExist = await _luminaDbContext.Libraries.AnyAsync(repositoryLibrary => repositoryLibrary.Id == library.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesLibraryExist) return Errors.Library.LibraryAlreadyExists; _luminaDbContext.Libraries.Add(library); @@ -52,11 +56,16 @@ internal sealed class LibraryRepository : ILibraryRepository /// The Id of the library to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.Libraries - .Include(library => library.ContentLocations) - .FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Libraries; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query + .Include(library => library.ContentLocations) + .AsSplitQuery(); + return await query.FirstOrDefaultAsync(library => library.Id == id, cancellationToken).ConfigureAwait(false); } /// @@ -68,6 +77,7 @@ internal sealed class LibraryRepository : ILibraryRepository { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .AsSplitQuery() .Where(library => library.IsEnabled) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -81,41 +91,94 @@ internal sealed class LibraryRepository : ILibraryRepository { return await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .AsSplitQuery() .Where(library => library.IsEnabled && !library.IsLocked) .ToListAsync(cancellationToken).ConfigureAwait(false); } /// - /// Gets all media libraries. + /// Gets all the media libraries, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching media libraries are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.Libraries - .Include(library => library.ContentLocations) + IQueryable query = _luminaDbContext.Libraries; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query + .Include(library => library.ContentLocations) + .AsSplitQuery(); + + // If no pagination was requested, return all the media libraries. + if (paginationData is null) + { + IReadOnlyList allLibraries = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allLibraries, + CurrentPage = 1, + PerPage = allLibraries.Count, + Count = allLibraries.Count, + NumberOfPages = 1 + }; + } + + int count = await query.Select(library => library.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// - /// Updates a media library. + /// Updates a media library, replacing only the editable data that actually changed, while preserving its identity, its audit columns, and the identity of its content locations. /// - /// The media library to update. + /// The media library whose editable data is applied to the stored library. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. public async Task> UpdateAsync(LibraryEntity data, CancellationToken cancellationToken) { LibraryEntity? foundLibrary = await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .AsSplitQuery() .FirstOrDefaultAsync(library => library.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundLibrary is null) return Errors.Library.LibraryNotFound; - // update scalar properties - _luminaDbContext.Entry(foundLibrary).CurrentValues.SetValues(data); - // update owned entities (their changes are not automatically tracked by EF) - foundLibrary.ContentLocations.Clear(); - foreach (LibraryContentLocationEntity contentLocation in data.ContentLocations) - foundLibrary.ContentLocations.Add(contentLocation); + + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibrary, data); + + // A content location is matched by its path. Matched locations keep their identity and the locations that did not change are left exactly as they are stored, + // so that editing a library never deletes and re-inserts all of its content locations. + CollectionReconciler.Reconcile( + foundLibrary.ContentLocations, + data.ContentLocations, + existingContentLocation => existingContentLocation.Path, + incomingContentLocation => incomingContentLocation.Path, + shouldReplace: (existingContentLocation, incomingContentLocation) => false, + createNew: incomingContentLocation => incomingContentLocation); + return Result.Updated; } @@ -129,6 +192,7 @@ internal sealed class LibraryRepository : ILibraryRepository { LibraryEntity? library = await _luminaDbContext.Libraries .Include(library => library.ContentLocations) + .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 6e072148..4c8a1c2a 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanRepository.cs @@ -2,6 +2,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Errors; @@ -39,9 +40,9 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(LibraryScanEntity libraryScan, CancellationToken cancellationToken) { - bool libraryScanExists = await _luminaDbContext.LibraryScans.AnyAsync( + bool doesLibraryScanExist = await _luminaDbContext.LibraryScans.AnyAsync( repositoryScanLibrary => repositoryScanLibrary.Id == libraryScan.Id, cancellationToken: cancellationToken).ConfigureAwait(false); - if (libraryScanExists) + if (doesLibraryScanExist) return Errors.LibraryScanning.LibraryScanAlreadyExists; _luminaDbContext.LibraryScans.Add(libraryScan); @@ -54,12 +55,17 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository /// The id of the library scan to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.LibraryScans - .Include(libraryScan => libraryScan.Library) - .Include(libraryScan => libraryScan.User) - .FirstOrDefaultAsync(libraryScan => libraryScan.Id == id, cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.LibraryScans; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query + .Include(libraryScan => libraryScan.Library) + .Include(libraryScan => libraryScan.User) + .AsSplitQuery(); + return await query.FirstOrDefaultAsync(libraryScan => libraryScan.Id == id, cancellationToken).ConfigureAwait(false); } /// @@ -71,6 +77,7 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository { return await _luminaDbContext.LibraryScans .Include(library => library.Library) + .AsSplitQuery() .Where(library => library.LibraryId == libraryId && library.CreatedOnUtc >= DateTime.UtcNow.AddMonths(-1)) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -84,6 +91,7 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository { return await _luminaDbContext.LibraryScans .Include(library => library.Library) + .AsSplitQuery() .Where(library => library.Status == LibraryScanJobStatus.Running) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -98,11 +106,12 @@ internal sealed class LibraryScanRepository : ILibraryScanRepository { LibraryScanEntity? foundLibraryScan = await _luminaDbContext.LibraryScans .Include(libraryScan => libraryScan.Library) + .AsSplitQuery() .FirstOrDefaultAsync(libraryScan => libraryScan.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundLibraryScan is null) return Errors.LibraryScanning.LibraryScanNotFound; - // update scalar properties - _luminaDbContext.Entry(foundLibraryScan).CurrentValues.SetValues(data); + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundLibraryScan, data); return Result.Updated; } } diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs new file mode 100644 index 00000000..a4d6a119 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -0,0 +1,300 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +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 albums. +/// +internal sealed class AlbumRepository : IAlbumRepository +{ + private readonly LuminaDbContext _luminaDbContext; + private readonly ITrackRepository _trackRepository; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + /// Injected repository for tracks. + public AlbumRepository(LuminaDbContext luminaDbContext, ITrackRepository trackRepository) + { + _luminaDbContext = luminaDbContext; + _trackRepository = trackRepository; + } + + /// + /// Adds a new album. + /// + /// The album to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(AlbumEntity album, CancellationToken cancellationToken) + { + bool doesAlbumExist = await _luminaDbContext.Albums.AnyAsync(repositoryAlbum => repositoryAlbum.Id == album.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesAlbumExist) + return Errors.Music.AlbumAlreadyExists; + + // A track is unique within its library by its file system path, so the same file can never be registered twice, neither twice in the same request, + // nor once when it is already registered in the library. The check runs here, for the whole album, because the insert of the album inserts its tracks as well. + Result checkTrackPathsResult = await CheckTrackPathsAsync(album, cancellationToken).ConfigureAwait(false); + if (checkTrackPathsResult.IsFailure) + return checkTrackPathsResult.Errors; + + // Resolve the tags and genres referenced by the album and its tracks to a single instance per name, replacing the stored ones where they exist, so that + // neither a stored row nor a name shared by the album and its tracks of the same request is tracked more than once. + Result> resolveTagsResult = await SharedReferenceResolver.ResolveAsync( + _luminaDbContext, album.Tags.Concat(album.Tracks.SelectMany(track => track.Tags)), Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveTagsResult.IsFailure) + return resolveTagsResult.Errors; + Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync( + _luminaDbContext, album.Genres.Concat(album.Tracks.SelectMany(track => track.Genres)), Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveGenresResult.IsFailure) + return resolveGenresResult.Errors; + + album.Tags = [.. SharedReferenceResolver.Normalize(album.Tags, resolveTagsResult.Value)]; + album.Genres = [.. SharedReferenceResolver.Normalize(album.Genres, resolveGenresResult.Value)]; + + foreach (TrackEntity track in album.Tracks) + { + track.Tags = [.. SharedReferenceResolver.Normalize(track.Tags, resolveTagsResult.Value)]; + track.Genres = [.. SharedReferenceResolver.Normalize(track.Genres, resolveGenresResult.Value)]; + } + + _luminaDbContext.Albums.Add(album); + return Result.Created; + } + + /// + /// Checks whether the tracks carried by reference a file system path that is already used by a track of the same library. + /// + /// The album whose track paths are checked. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful check, or an error. + private async Task> CheckTrackPathsAsync(AlbumEntity album, CancellationToken cancellationToken) + { + List trackPaths = [.. album.Tracks.Select(track => track.Path!)]; + if (trackPaths.Count == 0) + return Result.Success; + + // The same path cannot be referenced by two tracks of the request itself, not only by a track that is already stored. + if (trackPaths.Count != trackPaths.Distinct(StringComparer.Ordinal).Count()) + return Errors.Music.TrackAlreadyExists; + + Result> getExistingPathsResult = await _trackRepository.GetExistingPathsAsync(album.LibraryId, trackPaths, cancellationToken).ConfigureAwait(false); + if (getExistingPathsResult.IsFailure) + return getExistingPathsResult.Errors; + if (getExistingPathsResult.Value.Count > 0) + return Errors.Music.TrackAlreadyExists; + return Result.Success; + } + + /// + /// Updates an existing album, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns. + /// + /// The album whose editable data is applied to the stored album. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(AlbumEntity data, CancellationToken cancellationToken) + { + // Every collection that is reconciled must be loaded, so that the reconciliation can see the rows that are already stored and leave the unchanged ones alone. + AlbumEntity? foundAlbum = await _luminaDbContext.Albums + .Include(repositoryAlbum => repositoryAlbum.Tags) + .Include(repositoryAlbum => repositoryAlbum.Genres) + .Include(repositoryAlbum => repositoryAlbum.Ratings) + .Include(repositoryAlbum => repositoryAlbum.Contributors) + .AsSplitQuery() + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundAlbum is null) + return Errors.Music.AlbumNotFound; + + return await ApplyUpdateAsync(foundAlbum, data, cancellationToken).ConfigureAwait(false); + } + + /// + /// Applies the editable data of onto the already tracked , without loading it, so that a caller that already + /// loaded the album graph, like the artist repository, does not make the album repository load it again. + /// + /// The tracked album whose editable data is applied. + /// The album carrying the desired data. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ApplyUpdateAsync(AlbumEntity foundAlbum, AlbumEntity data, CancellationToken cancellationToken) + { + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + Guid artistId = foundAlbum.ArtistId; + Guid libraryId = foundAlbum.LibraryId; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundAlbum, data); + foundAlbum.ArtistId = artistId; + foundAlbum.LibraryId = libraryId; + + // Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted. + Result reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundAlbum.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileGenresResult.IsFailure) + return reconcileGenresResult.Errors; + + // Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change + // are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the album. + CollectionReconciler.Reconcile( + foundAlbum.Ratings, + data.Ratings, + existingRating => existingRating.Source?.ToString() ?? string.Empty, + incomingRating => incomingRating.Source?.ToString() ?? string.Empty, + shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating), + createNew: incomingRating => incomingRating); + + // A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a + // contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another album of the same artist was edited. + CollectionReconciler.Reconcile( + foundAlbum.Contributors, + data.Contributors, + existingContributor => (existingContributor.MediaContributorId, existingContributor.Role), + incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role), + shouldReplace: (existingContributor, incomingContributor) => false, + createNew: incomingContributor => incomingContributor); + + return Result.Updated; + } + + /// + /// Gets an album by its Id. + /// + /// The Id of the album to get. + /// Whether the navigation properties of the album should be loaded together with the album itself. + /// Whether the retrieved album should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// An containing either an , or an error. + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) + { + IQueryable query = _luminaDbContext.Albums; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + query = query + .Include(album => album.Artist) + .Include(album => album.Ratings) + .Include(album => album.Tags) + .Include(album => album.Genres) + .Include(album => album.Contributors) + .Include(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .Include(album => album.Tracks) + .ThenInclude(track => track.Genres) + .Include(album => album.Tracks) + .ThenInclude(track => track.Tags) + .Include(album => album.Tracks) + .ThenInclude(track => track.Moods) + .Include(album => album.Tracks) + .ThenInclude(track => track.Isrcs) + .Include(album => album.Tracks) + .ThenInclude(track => track.Contributors) + .AsSplitQuery(); + } + return await query.FirstOrDefaultAsync(album => album.Id == id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets all the albums of the artist identified by . + /// + /// The Id of the artist whose albums are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByArtistIdAsync(Guid artistId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Albums + .Include(album => album.Ratings) + .Include(album => album.Tags) + .Include(album => album.Genres) + .Include(album => album.Contributors) + .Include(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .Include(album => album.Tracks) + .ThenInclude(track => track.Genres) + .Include(album => album.Tracks) + .ThenInclude(track => track.Tags) + .Include(album => album.Tracks) + .ThenInclude(track => track.Moods) + .Include(album => album.Tracks) + .ThenInclude(track => track.Isrcs) + .Include(album => album.Tracks) + .ThenInclude(track => track.Contributors) + .AsSplitQuery() + .Where(album => album.ArtistId == artistId) + .OrderBy(album => album.Title) + .ThenBy(album => album.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the lightweight read models of the albums of the artist identified by , + /// or all of them when the pagination data is , projecting only the fields needed to display the albums in a card-based grid. + /// + /// The Id of the artist whose albums are retrieved. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching albums are returned. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> GetAlbumsLiteByArtistIdAsync(Guid artistId, PaginationDataDto? paginationData, CancellationToken cancellationToken) + { + // The lightweight read models are always retrieved without tracking, because they are never modified by the caller. + IQueryable liteRowsQuery = _luminaDbContext.Albums + .AsNoTracking() + .Where(album => album.ArtistId == artistId) + .OrderBy(album => album.Title) + .ThenBy(album => album.Id) + .Select(album => new AlbumLiteRow + { + Id = album.Id, + Title = album.Title, + TotalTracks = album.TotalTracks + }); + + if (paginationData is null) + { + IReadOnlyList allAlbums = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allAlbums, + CurrentPage = 1, + PerPage = allAlbums.Count, + Count = allAlbums.Count, + NumberOfPages = 1 + }; + } + + int count = await liteRowsQuery.CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); + + IReadOnlyList paginatedResult = await liteRowsQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs new file mode 100644 index 00000000..7387003e --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -0,0 +1,590 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Specifications; +using Lumina.DataAccess.Common.Persistence; +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.Common; +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 artists. +/// +internal sealed class ArtistRepository : IArtistRepository +{ + private readonly LuminaDbContext _luminaDbContext; + private readonly IAlbumRepository _albumRepository; + private readonly ITrackRepository _trackRepository; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + /// Injected repository for albums. + /// Injected repository for tracks. + public ArtistRepository(LuminaDbContext luminaDbContext, IAlbumRepository albumRepository, ITrackRepository trackRepository) + { + _luminaDbContext = luminaDbContext; + _albumRepository = albumRepository; + _trackRepository = trackRepository; + } + + /// + /// Adds a new artist. + /// + /// The artist to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(ArtistEntity artist, CancellationToken cancellationToken) + { + bool doesArtistExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.Id == artist.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesArtistExist) + return Errors.Music.ArtistAlreadyExists; + + // An artist is unique within its library by its name, so the same artist can never be registered twice in the same library. + bool doesArtistNameExist = await _luminaDbContext.Artists.AnyAsync(repositoryArtist => repositoryArtist.LibraryId == artist.LibraryId && repositoryArtist.Name == artist.Name, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesArtistNameExist) + return Errors.Music.ArtistAlreadyExists; + + // A track is unique within its library by its file system path, so the same file can never be registered twice, neither twice in the same request, + // nor once when it is already registered in the library. The check runs here, for the whole artist, because the insert of the artist inserts its albums and their tracks as well. + List trackPaths = [.. artist.Albums.SelectMany(album => album.Tracks).Select(track => track.Path!)]; + Result checkTrackPathsResult = await CheckTrackPathsAsync(artist.LibraryId, trackPaths, cancellationToken).ConfigureAwait(false); + if (checkTrackPathsResult.IsFailure) + return checkTrackPathsResult.Errors; + + // Resolve the tags and genres referenced anywhere in the aggregate to a single instance per name, replacing the stored ones where they exist, so that + // 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))), + Errors.Metadata.TagNameCannotBeEmpty, + cancellationToken).ConfigureAwait(false); + if (resolveTagsResult.IsFailure) + return resolveTagsResult.Errors; + + Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync( + _luminaDbContext, + 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; + + foreach (AlbumEntity album in artist.Albums) + { + album.Tags = [.. SharedReferenceResolver.Normalize(album.Tags, resolveTagsResult.Value)]; + album.Genres = [.. SharedReferenceResolver.Normalize(album.Genres, resolveGenresResult.Value)]; + + foreach (TrackEntity track in album.Tracks) + { + track.Tags = [.. SharedReferenceResolver.Normalize(track.Tags, resolveTagsResult.Value)]; + track.Genres = [.. SharedReferenceResolver.Normalize(track.Genres, resolveGenresResult.Value)]; + } + } + + _luminaDbContext.Artists.Add(artist); + return Result.Created; + } + + /// + /// Updates an existing artist, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns. + /// + /// The artist whose editable data is applied to the stored artist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(ArtistEntity data, CancellationToken cancellationToken) + { + // 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.Contributors) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tags) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Genres) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Ratings) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Contributors) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Tags) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Genres) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Moods) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Isrcs) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Contributors) + .AsSplitQuery() + .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundArtist is null) + return Errors.Music.ArtistNotFound; + + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + Guid libraryId = foundArtist.LibraryId; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundArtist, data); + foundArtist.LibraryId = libraryId; + + // A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a + // contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another field of the artist was edited. + CollectionReconciler.Reconcile( + foundArtist.Contributors, + data.Contributors, + existingContributor => (existingContributor.MediaContributorId, existingContributor.Role), + incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role), + shouldReplace: (existingContributor, incomingContributor) => false, + createNew: incomingContributor => incomingContributor); + + // 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)]; + Result checkNewTrackPathsResult = await CheckTrackPathsAsync(foundArtist.LibraryId, newTrackPaths, cancellationToken).ConfigureAwait(false); + if (checkNewTrackPathsResult.IsFailure) + return checkNewTrackPathsResult.Errors; + + // Normalize the tags and genres carried by the desired aggregate, so that a name shared by several albums or tracks is represented by a single instance, + // 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))), + 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))), + Errors.Metadata.GenreNameCannotBeEmpty, + cancellationToken).ConfigureAwait(false); + if (resolveGenresResult.IsFailure) + return resolveGenresResult.Errors; + + foreach (AlbumEntity dataAlbum in data.Albums) + { + dataAlbum.Tags = [.. SharedReferenceResolver.Normalize(dataAlbum.Tags, resolveTagsResult.Value)]; + dataAlbum.Genres = [.. SharedReferenceResolver.Normalize(dataAlbum.Genres, resolveGenresResult.Value)]; + + foreach (TrackEntity dataTrack in dataAlbum.Tracks) + { + dataTrack.Tags = [.. SharedReferenceResolver.Normalize(dataTrack.Tags, resolveTagsResult.Value)]; + dataTrack.Genres = [.. SharedReferenceResolver.Normalize(dataTrack.Genres, resolveGenresResult.Value)]; + } + } + + // Reconcile the albums by their Id: albums that are no longer present are removed, new albums are inserted, and existing + // albums and their tracks are updated in place, so that persisted entities keep their identity across an edit. An album whose data did + // not change produces no write statement, because its own repository only applies the values that actually changed. + List incomingAlbumIds = [.. data.Albums.Select(album => album.Id)]; + foreach (AlbumEntity removedAlbum in foundArtist.Albums.Where(album => !incomingAlbumIds.Contains(album.Id)).ToList()) + foundArtist.Albums.Remove(removedAlbum); + + foreach (AlbumEntity incomingAlbum in data.Albums) + { + AlbumEntity? existingAlbum = foundArtist.Albums.FirstOrDefault(album => album.Id == incomingAlbum.Id); + if (existingAlbum is null) + { + Result insertAlbumResult = await _albumRepository.InsertAsync(incomingAlbum, cancellationToken).ConfigureAwait(false); + if (insertAlbumResult.IsFailure) + return insertAlbumResult.Errors; + continue; + } + + Result updateAlbumResult = await _albumRepository.ApplyUpdateAsync(existingAlbum, incomingAlbum, cancellationToken).ConfigureAwait(false); + if (updateAlbumResult.IsFailure) + return updateAlbumResult.Errors; + + Result updateTracksResult = await ReconcileTracksAsync(existingAlbum, incomingAlbum, cancellationToken).ConfigureAwait(false); + if (updateTracksResult.IsFailure) + return updateTracksResult.Errors; + } + + return Result.Updated; + } + + /// + /// Gets the file system paths of the tracks that are not yet stored and will therefore be inserted when is applied over . + /// + /// The tracked artist that is being updated. + /// The artist carrying the desired albums and tracks. + /// The file system paths of the tracks that are about to be inserted. + private static IEnumerable GetNewTrackPaths(ArtistEntity foundArtist, ArtistEntity data) + { + foreach (AlbumEntity incomingAlbum in data.Albums) + { + AlbumEntity? existingAlbum = foundArtist.Albums.FirstOrDefault(album => album.Id == incomingAlbum.Id); + if (existingAlbum is null) + { + foreach (TrackEntity incomingTrack in incomingAlbum.Tracks) + yield return incomingTrack.Path!; + continue; + } + + foreach (TrackEntity incomingTrack in incomingAlbum.Tracks) + if (existingAlbum.Tracks.All(existingTrack => existingTrack.Id != incomingTrack.Id)) + yield return incomingTrack.Path!; + } + } + + /// + /// Checks whether any of is referenced more than once, or is already used by a track of the library identified by . + /// + /// The Id of the library whose tracks are searched. + /// The file system paths of the tracks that are about to be inserted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful check, or an error. + private async Task> CheckTrackPathsAsync(Guid libraryId, IReadOnlyCollection trackPaths, CancellationToken cancellationToken) + { + if (trackPaths.Count == 0) + return Result.Success; + + // The same path cannot be referenced by two tracks of the request itself, not only by a track that is already stored. + if (trackPaths.Count != trackPaths.Distinct(StringComparer.Ordinal).Count()) + return Errors.Music.TrackAlreadyExists; + + Result> getExistingPathsResult = await _trackRepository.GetExistingPathsAsync(libraryId, trackPaths, cancellationToken).ConfigureAwait(false); + if (getExistingPathsResult.IsFailure) + return getExistingPathsResult.Errors; + if (getExistingPathsResult.Value.Count > 0) + return Errors.Music.TrackAlreadyExists; + return Result.Success; + } + + /// + /// Reconciles the tracks of an existing album against the provided tracks, by their Id. + /// + /// The tracked album whose tracks are reconciled. + /// The album carrying the tracks to reconcile with. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ReconcileTracksAsync(AlbumEntity existingAlbum, AlbumEntity incomingAlbum, CancellationToken cancellationToken) + { + List incomingTrackIds = [.. incomingAlbum.Tracks.Select(track => track.Id)]; + foreach (TrackEntity removedTrack in existingAlbum.Tracks.Where(track => !incomingTrackIds.Contains(track.Id)).ToList()) + existingAlbum.Tracks.Remove(removedTrack); + + foreach (TrackEntity incomingTrack in incomingAlbum.Tracks) + { + incomingTrack.AlbumId = existingAlbum.Id; + incomingTrack.LibraryId = existingAlbum.LibraryId; + TrackEntity? existingTrack = existingAlbum.Tracks.FirstOrDefault(track => track.Id == incomingTrack.Id); + if (existingTrack is null) + { + Result insertTrackResult = await _trackRepository.InsertAsync(incomingTrack, cancellationToken).ConfigureAwait(false); + if (insertTrackResult.IsFailure) + return insertTrackResult.Errors; + continue; + } + + Result updateTrackResult = await _trackRepository.ApplyUpdateAsync(existingTrack, incomingTrack, cancellationToken).ConfigureAwait(false); + if (updateTrackResult.IsFailure) + return updateTrackResult.Errors; + } + + return Result.Updated; + } + + /// + /// Gets an artist by its Id. + /// + /// The Id of the artist to get. + /// Whether the navigation properties of the artist should be loaded together with the artist itself. + /// Whether the retrieved artist should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// An containing either an , or an error. + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) + { + IQueryable query = _luminaDbContext.Artists; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + query = query + .Include(artist => artist.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Ratings) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Genres) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tags) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .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.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) + .AsSplitQuery(); + } + return await query.FirstOrDefaultAsync(artist => artist.Id == id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes the artist identified by . + /// + /// The Id of the artist 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) + { + ArtistEntity? artist = await _luminaDbContext.Artists + .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == id, cancellationToken).ConfigureAwait(false); + if (artist is null) + return Errors.Music.ArtistNotFound; + + _luminaDbContext.Artists.Remove(artist); + return Result.Deleted; + } + + /// + /// Gets paginated artists, or all the artists of the matching filters when the pagination data is . + /// + /// The type of the filter used for filtering the data. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching artists are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + { + IQueryable artistsQuery = _luminaDbContext.Artists; + if (!shouldTrackEntities) + artistsQuery = artistsQuery.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + artistsQuery = artistsQuery + .Include(artist => artist.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Ratings) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Genres) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tags) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .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.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) + .AsSplitQuery(); + } + + // Artists should always be retrieved only per owning libraries. + if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) + return Errors.Library.FilterMustIncludeLibraryId; + + artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId); + + FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter); + if (filterSpecification is not null) + artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); + + IQueryable orderedArtistsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending); + + // If no pagination was requested, return all the artists of the library. + if (paginationData is null) + { + IReadOnlyList allArtists = await orderedArtistsQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allArtists, + CurrentPage = 1, + PerPage = allArtists.Count, + Count = allArtists.Count, + NumberOfPages = 1 + }; + } + + int count = await orderedArtistsQuery.Select(artist => artist.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); + + // Apply pagination. + IReadOnlyList paginatedResult = await orderedArtistsQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + + /// + /// Gets paginated lightweight read models of the artists of the media library identified by the provided , + /// or all of them when the pagination data is , projecting only the fields needed to display the artists in a card-based grid. + /// + /// The type of the filter used for filtering the data. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching artists are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> GetAllLiteAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + { + // Artists should always be retrieved only per owning libraries. + if (filterModel is not LibraryFilterDto libraryFilter || libraryFilter.LibraryId == Guid.Empty) + return Errors.Library.FilterMustIncludeLibraryId; + + // The lightweight read models are retrieved without tracking by default, because they are never modified by the caller. + IQueryable artistsQuery = _luminaDbContext.Artists; + if (!shouldTrackEntities) + artistsQuery = artistsQuery.AsNoTracking(); + if (shouldIncludeNavigationProperties) + artistsQuery = artistsQuery + .Include(artist => artist.Contributors) + .Include(artist => artist.Albums) + .AsSplitQuery(); + + artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId); + + FilterSpecification? filterSpecification = BuildFilterSpecification(libraryFilter); + if (filterSpecification is not null) + artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); + + IQueryable liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending) + .Select(artist => new ArtistLiteRow + { + Id = artist.Id, + Name = artist.Name + }); + + // If no pagination was requested, return all the artists of the library. + if (paginationData is null) + { + IReadOnlyList allArtists = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allArtists, + CurrentPage = 1, + PerPage = allArtists.Count, + Count = allArtists.Count, + NumberOfPages = 1 + }; + } + + int count = await artistsQuery.Select(artist => artist.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); + + // Apply pagination. + IReadOnlyList paginatedResult = await liteRowsQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } + + /// + /// Builds a filter specification for querying artists. + /// + /// The model containing the parameters used to filter the results. + /// A filter specification that can be used to query artists matching the provided criteria. + private static FilterSpecification? BuildFilterSpecification(LibraryFilterDto libraryFilter) + { + // Include the search term filter, if provided. + if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) + return new ArtistSearchSpecification(libraryFilter.SearchTerm); + + return null; + } + + /// + /// Sorts an artists query by the given field name, defaulting to . + /// + /// The query to sort. + /// The field to sort by (case-insensitive). + /// The direction of the sorting. + /// An ordered artists query. + private static IOrderedQueryable ApplySorting(IQueryable artistsQuery, string? sortBy, SortOrder sortOrder) + { + return sortBy?.ToLowerInvariant() switch + { + "website" => sortOrder == SortOrder.Descending + ? artistsQuery.OrderByDescending(artist => artist.Website).ThenBy(artist => artist.Id) + : artistsQuery.OrderBy(artist => artist.Website).ThenBy(artist => artist.Id), + "musicbrainzartistid" => sortOrder == SortOrder.Descending + ? artistsQuery.OrderByDescending(artist => artist.MusicBrainzArtistId).ThenBy(artist => artist.Id) + : artistsQuery.OrderBy(artist => artist.MusicBrainzArtistId).ThenBy(artist => artist.Id), + "createdonutc" => sortOrder == SortOrder.Descending + ? artistsQuery.OrderByDescending(artist => artist.CreatedOnUtc).ThenBy(artist => artist.Id) + : artistsQuery.OrderBy(artist => artist.CreatedOnUtc).ThenBy(artist => artist.Id), + "updatedonutc" => sortOrder == SortOrder.Descending + ? artistsQuery.OrderByDescending(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id) + : artistsQuery.OrderBy(artist => artist.UpdatedOnUtc).ThenBy(artist => artist.Id), + _ => sortOrder == SortOrder.Descending + ? artistsQuery.OrderByDescending(artist => artist.Name).ThenBy(artist => artist.Id) + : artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id), + }; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecification.cs new file mode 100644 index 00000000..2766c7c9 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecification.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Specifications; +using System; +using System.Linq.Expressions; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.MusicLibrary.Specifications; + +/// +/// Represents a filter specification for filtering or searching artist entities based on a search term. +/// +internal sealed class ArtistSearchSpecification : FilterSpecification +{ + private readonly string _searchTerm; + + /// + /// Initializes a new instance of the class. + /// + /// The term to use when filtering or searching for artists. + public ArtistSearchSpecification(string searchTerm) + { + _searchTerm = searchTerm; + } + + /// + /// Creates a LINQ expression that represents the predicate defined by the current specification. + /// + /// An expression tree that can be used to evaluate whether an satisfies the specification criteria. + public override Expression> ToExpression() + { + // The term is normalized with the invariant culture, so that the case folding never depends on the current culture. The column is folded by the storage medium, which keeps the search case-insensitive. + string normalizedSearchTerm = _searchTerm.ToLowerInvariant(); +#pragma warning disable IDE0079 // Remove unnecessary suppression. +#pragma warning disable CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string comparisons. This expression is translated to SQL; the StringComparison overloads are client-side only and are not translated, so they would fail at query time. + return artist => artist.Name.ToLower().Contains(normalizedSearchTerm); +#pragma warning restore CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string comparisons. +#pragma warning restore IDE0079 // Remove unnecessary suppression. + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs new file mode 100644 index 00000000..de46fe87 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -0,0 +1,289 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +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 tracks. +/// +internal sealed class TrackRepository : ITrackRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public TrackRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new track. + /// + /// The track to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertAsync(TrackEntity track, CancellationToken cancellationToken) + { + bool doesTrackExist = await _luminaDbContext.Tracks.AnyAsync(repositoryTrack => repositoryTrack.Id == track.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesTrackExist) + return Errors.Music.TrackAlreadyExists; + + // A track is unique within its library by its file system path, so the same file can never be registered twice in the same library. + Result> getExistingPathsResult = await GetExistingPathsAsync(track.LibraryId, [track.Path], cancellationToken).ConfigureAwait(false); + if (getExistingPathsResult.IsFailure) + return getExistingPathsResult.Errors; + if (getExistingPathsResult.Value.Count > 0) + return Errors.Music.TrackAlreadyExists; + + // Resolve the tags and genres of the track to a single instance per name, replacing the stored ones where they exist, so that the shared tables are not duplicated. + Result> resolveTagsResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, track.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveTagsResult.IsFailure) + return resolveTagsResult.Errors; + Result> resolveGenresResult = await SharedReferenceResolver.ResolveAsync(_luminaDbContext, track.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (resolveGenresResult.IsFailure) + return resolveGenresResult.Errors; + + track.Tags = [.. SharedReferenceResolver.Normalize(track.Tags, resolveTagsResult.Value)]; + track.Genres = [.. SharedReferenceResolver.Normalize(track.Genres, resolveGenresResult.Value)]; + + _luminaDbContext.Tracks.Add(track); + return Result.Created; + } + + /// + /// Gets the subset of that is already used by a track of the library identified by . + /// + /// The Id of the library whose tracks are searched. + /// The track 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.Tracks + .Where(repositoryTrack => repositoryTrack.LibraryId == libraryId && distinctPaths.Contains(repositoryTrack.Path)) + .Select(repositoryTrack => repositoryTrack.Path) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From>(existingPaths); + } + + /// + /// Updates an existing track, replacing only the editable data that actually changed, while preserving its identity, the identity of its children, and its audit columns. + /// + /// The track whose editable data is applied to the stored track. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(TrackEntity data, CancellationToken cancellationToken) + { + // Every collection that is reconciled must be loaded, so that the reconciliation can see the rows that are already stored and leave the unchanged ones alone. + TrackEntity? foundTrack = await _luminaDbContext.Tracks + .Include(repositoryTrack => repositoryTrack.Tags) + .Include(repositoryTrack => repositoryTrack.Genres) + .Include(repositoryTrack => repositoryTrack.Ratings) + .Include(repositoryTrack => repositoryTrack.Contributors) + .Include(repositoryTrack => repositoryTrack.Moods) + .Include(repositoryTrack => repositoryTrack.Isrcs) + .AsSplitQuery() + .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (foundTrack is null) + return Errors.Music.TrackNotFound; + + return await ApplyUpdateAsync(foundTrack, data, cancellationToken).ConfigureAwait(false); + } + + /// + /// Applies the editable data of onto the already tracked , without loading it, so that a caller that already + /// loaded the track graph, like the artist repository, does not make the track repository load it again. + /// + /// The tracked track whose editable data is applied. + /// The track carrying the desired data. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> ApplyUpdateAsync(TrackEntity foundTrack, TrackEntity data, CancellationToken cancellationToken) + { + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + Guid albumId = foundTrack.AlbumId; + Guid libraryId = foundTrack.LibraryId; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTrack, data); + foundTrack.AlbumId = albumId; + foundTrack.LibraryId = libraryId; + + // Tags and genres are shared across the whole database, so the stored rows whose names already exist are reused, and only the missing names are inserted. + Result reconcileTagsResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Tags, data.Tags, Errors.Metadata.TagNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileTagsResult.IsFailure) + return reconcileTagsResult.Errors; + Result reconcileGenresResult = await SharedReferenceResolver.ReconcileAsync(_luminaDbContext, foundTrack.Genres, data.Genres, Errors.Metadata.GenreNameCannotBeEmpty, cancellationToken).ConfigureAwait(false); + if (reconcileGenresResult.IsFailure) + return reconcileGenresResult.Errors; + + // Ratings are owned value objects with no identity anyone could reference, so a changed rating is replaced as a whole, while the ratings that did not change + // are left exactly as they are stored. Matching by the rating source keeps an update in place instead of recreating every rating of the track. + CollectionReconciler.Reconcile( + foundTrack.Ratings, + data.Ratings, + existingRating => existingRating.Source?.ToString() ?? string.Empty, + incomingRating => incomingRating.Source?.ToString() ?? string.Empty, + shouldReplace: (existingRating, incomingRating) => !existingRating.Equals(incomingRating), + createNew: incomingRating => incomingRating); + + // A contributor participation is matched by the contributor and the role they played. Matched participations keep their identity and their audit columns, so a + // contributor that is displayed or linked elsewhere is never deleted and re-inserted just because another track of the same album was edited. + CollectionReconciler.Reconcile( + foundTrack.Contributors, + data.Contributors, + existingContributor => (existingContributor.MediaContributorId, existingContributor.Role), + incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role), + shouldReplace: (existingContributor, incomingContributor) => false, + createNew: incomingContributor => incomingContributor); + + // Moods and ISRCs are owned value objects whose value is also their identity, so a match means there is nothing to change. + CollectionReconciler.Reconcile( + foundTrack.Moods, + data.Moods, + existingMood => existingMood.Name, + incomingMood => incomingMood.Name, + shouldReplace: (existingMood, incomingMood) => false, + createNew: incomingMood => incomingMood); + + CollectionReconciler.Reconcile( + foundTrack.Isrcs, + data.Isrcs, + existingIsrc => existingIsrc.Value, + incomingIsrc => incomingIsrc.Value, + shouldReplace: (existingIsrc, incomingIsrc) => false, + createNew: incomingIsrc => incomingIsrc); + + return Result.Updated; + } + + /// + /// Gets a track by its Id. + /// + /// The Id of the track to get. + /// Whether the navigation properties of the track should be loaded together with the track itself. + /// Whether the retrieved track should be tracked by the persistence medium, so that changes to it can be saved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) + { + IQueryable query = _luminaDbContext.Tracks; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + { + query = query + .Include(track => track.Album) + .ThenInclude(album => album!.Artist) + .Include(track => track.Ratings) + .Include(track => track.Tags) + .Include(track => track.Genres) + .Include(track => track.Moods) + .Include(track => track.Isrcs) + .Include(track => track.Contributors) + .AsSplitQuery(); + } + return await query.FirstOrDefaultAsync(track => track.Id == id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets all the tracks of the album identified by . + /// + /// The Id of the album whose tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByAlbumIdAsync(Guid albumId, CancellationToken cancellationToken) + { + return await _luminaDbContext.Tracks + .Include(track => track.Ratings) + .Include(track => track.Tags) + .Include(track => track.Genres) + .Include(track => track.Moods) + .Include(track => track.Isrcs) + .Include(track => track.Contributors) + .AsSplitQuery() + .Where(track => track.AlbumId == albumId) + .OrderBy(track => track.DiscNumber) + .ThenBy(track => track.TrackNumber) + .ThenBy(track => track.Id) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the lightweight read models of the tracks of the album identified by , + /// or all of them when the pagination data is , projecting only the fields needed to display the tracks of an album. + /// + /// The Id of the album whose tracks are retrieved. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all matching tracks are returned. + /// Cancellation token that can be used to stop the execution. + /// An containing either a , or an error. + public async Task>> GetTracksLiteByAlbumIdAsync(Guid albumId, PaginationDataDto? paginationData, CancellationToken cancellationToken) + { + // The lightweight read models are always retrieved without tracking, because they are never modified by the caller. + IQueryable liteRowsQuery = _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => track.AlbumId == albumId) + .OrderBy(track => track.DiscNumber) + .ThenBy(track => track.TrackNumber) + .ThenBy(track => track.Id) + .Select(track => new TrackLiteRow + { + Id = track.Id, + Title = track.Title, + TrackNumber = track.TrackNumber, + DiscNumber = track.DiscNumber + }); + + if (paginationData is null) + { + IReadOnlyList allTracks = await liteRowsQuery.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allTracks, + CurrentPage = 1, + PerPage = allTracks.Count, + Count = allTracks.Count, + NumberOfPages = 1 + }; + } + + int count = await liteRowsQuery.CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); + + IReadOnlyList paginatedResult = await liteRowsQuery + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs index c71d54fd..7d3d7b4c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/PluginRepository.cs @@ -2,11 +2,15 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -35,21 +39,63 @@ internal sealed class PluginRepository : IPluginRepository /// The Id of the plugin to get. /// Cancellation token that can be used to stop the execution. /// An containing either a , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.Plugins - .FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Plugins; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false); } /// - /// Gets all the detected plugins. + /// Gets all the detected plugins, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching plugins are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.Plugins + IQueryable query = _luminaDbContext.Plugins; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the plugins. + if (paginationData is null) + { + IReadOnlyList allPlugins = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allPlugins, + CurrentPage = 1, + PerPage = allPlugins.Count, + Count = allPlugins.Count, + NumberOfPages = 1 + }; + } + + int count = await query.Select(plugin => plugin.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -66,7 +112,7 @@ internal sealed class PluginRepository : IPluginRepository _luminaDbContext.Plugins.Add(plugin); else { - // update only the detection fields, preserving the stored settings and creation date + // Update only the detection fields, preserving the stored settings and creation date. existingPlugin.Name = plugin.Name; existingPlugin.Author = plugin.Author; existingPlugin.Version = plugin.Version; diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs index 32f4fa45..ae14ea56 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobExecutionRepository.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -36,11 +37,14 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe /// The id of the execution to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - // FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only - // reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again. - return await _luminaDbContext.ScheduledJobExecutions.FindAsync([id], cancellationToken).ConfigureAwait(false); + // The execution is read with a query instead of FindAsync so that it can be retrieved without tracking when requested. + // When the entity is tracked, the change tracker still returns the already loaded instance instead of a new one. + IQueryable query = _luminaDbContext.ScheduledJobExecutions; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(execution => execution.Id == id, cancellationToken).ConfigureAwait(false); } /// @@ -72,8 +76,8 @@ internal sealed class ScheduledJobExecutionRepository : IScheduledJobExecutionRe ?? await _luminaDbContext.ScheduledJobExecutions.FirstOrDefaultAsync(execution => execution.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundExecution is null) return Errors.Scheduling.ScheduledJobExecutionNotFound; - // Update scalar properties. - _luminaDbContext.Entry(foundExecution).CurrentValues.SetValues(data); + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundExecution, data); return Result.Updated; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs index 899b05fb..60f7ec50 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Scheduling/ScheduledJobRepository.cs @@ -1,9 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +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.Common; using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using Microsoft.EntityFrameworkCore; using System; @@ -37,11 +41,14 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository /// The id of the scheduled job to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - // FindAsync returns an entity that was already loaded in the current unit of work from the change tracker, and only - // reads it from the storage medium when it is not tracked, so an entity loaded earlier is not read again. - return await _luminaDbContext.ScheduledJobs.FindAsync([id], cancellationToken).ConfigureAwait(false); + // The scheduled job is read with a query instead of FindAsync so that it can be retrieved without tracking when requested. + // When the entity is tracked, the change tracker still returns the already loaded instance instead of a new one. + IQueryable query = _luminaDbContext.ScheduledJobs; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == id, cancellationToken).ConfigureAwait(false); } /// @@ -59,14 +66,54 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository } /// - /// Gets all scheduled jobs from the storage medium. + /// Gets all the scheduled jobs from the storage medium, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching scheduled jobs are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.ScheduledJobs + IQueryable query = _luminaDbContext.ScheduledJobs; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the scheduled jobs. + if (paginationData is null) + { + IReadOnlyList allScheduledJobs = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allScheduledJobs, + CurrentPage = 1, + PerPage = allScheduledJobs.Count, + Count = allScheduledJobs.Count, + NumberOfPages = 1 + }; + } + + int count = await query.Select(scheduledJob => scheduledJob.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -110,8 +157,8 @@ internal sealed class ScheduledJobRepository : IScheduledJobRepository ?? await _luminaDbContext.ScheduledJobs.FirstOrDefaultAsync(scheduledJob => scheduledJob.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundScheduledJob is null) return Errors.Scheduling.ScheduledJobNotFound; - // Update scalar properties. - _luminaDbContext.Entry(foundScheduledJob).CurrentValues.SetValues(data); + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundScheduledJob, data); return Result.Updated; } diff --git a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs index 330b06ce..7cdd6973 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Themes/ThemeRepository.cs @@ -2,8 +2,12 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; @@ -38,8 +42,8 @@ internal sealed class ThemeRepository : IThemeRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(ThemeEntity theme, CancellationToken cancellationToken) { - bool themeExists = await _luminaDbContext.Themes.AnyAsync(repositoryTheme => repositoryTheme.Id == theme.Id, cancellationToken).ConfigureAwait(false); - if (themeExists) + bool doesThemeExist = await _luminaDbContext.Themes.AnyAsync(repositoryTheme => repositoryTheme.Id == theme.Id, cancellationToken).ConfigureAwait(false); + if (doesThemeExist) return Errors.Themes.ThemeNotFound; _luminaDbContext.Themes.Add(theme); @@ -59,18 +63,60 @@ internal sealed class ThemeRepository : IThemeRepository if (foundTheme is null) return Errors.Themes.ThemeNotFound; - _luminaDbContext.Entry(foundTheme).CurrentValues.SetValues(data); + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundTheme, data); return Result.Updated; } /// - /// Gets all themes from the storage medium. + /// Gets all the themes from the storage medium, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching themes are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.Themes.ToListAsync(cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Themes; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the themes. + if (paginationData is null) + { + IReadOnlyList allThemes = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allThemes, + CurrentPage = 1, + PerPage = allThemes.Count, + Count = allThemes.Count, + NumberOfPages = 1 + }; + } + + int count = await query.Select(theme => theme.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs index 0414b5a9..2ee42ed7 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserRepository.cs @@ -3,11 +3,16 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.Common; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -38,8 +43,8 @@ internal sealed class UserRepository : IUserRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(UserEntity user, CancellationToken cancellationToken) { - bool userExists = await _luminaDbContext.Users.AnyAsync(repositoryUser => repositoryUser.Id == user.Id, cancellationToken: cancellationToken).ConfigureAwait(false); - if (userExists) + bool doesUserExist = await _luminaDbContext.Users.AnyAsync(repositoryUser => repositoryUser.Id == user.Id, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesUserExist) return Errors.Users.UserAlreadyExists; _luminaDbContext.Users.Add(user); @@ -47,13 +52,54 @@ internal sealed class UserRepository : IUserRepository } /// - /// Gets all users. + /// Gets all the users, or a page of them when the pagination data is provided. /// + /// The type of the filter carrying the criteria used to filter the results. + /// The pagination data that includes the current page and the number of items per page to retrieve. If , all the matching users are returned. + /// The name of the field by which to sort the results. + /// The direction in which to sort the results. + /// The model containing the parameters used to filter the results. + /// Whether the navigation properties of the entities should be loaded together with the entities themselves. Pass to retrieve only the data stored directly on the entity rows. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass for read-only scenarios, to avoid the tracking overhead. /// Cancellation token that can be used to stop the execution. - /// An containing either a collection of , or an error. - public async Task>> GetAllAsync(CancellationToken cancellationToken) + /// An containing either a paginated result of , or an error. + public async Task>> GetAllAsync(PaginationDataDto? paginationData = null, string? sortBy = null, SortOrder? sortOrder = null, TFilter? filterModel = null, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto { - return await _luminaDbContext.Users.ToListAsync(cancellationToken).ConfigureAwait(false); + IQueryable query = _luminaDbContext.Users; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + + // If no pagination was requested, return all the users. + if (paginationData is null) + { + IReadOnlyList allUsers = await query.ToListAsync(cancellationToken).ConfigureAwait(false); + return new PaginatedResultDto + { + Data = allUsers, + CurrentPage = 1, + PerPage = allUsers.Count, + Count = allUsers.Count, + NumberOfPages = 1 + }; + } + + int count = await query.Select(user => user.Id).CountAsync(cancellationToken).ConfigureAwait(false); + int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage); + int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages. + + IReadOnlyList paginatedResult = await query + .Skip((currentPage - 1) * paginationData.PerPage) + .Take(paginationData.PerPage) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + return new PaginatedResultDto + { + Data = paginatedResult, + CurrentPage = currentPage, + PerPage = paginationData.PerPage, + Count = count, + NumberOfPages = numberOfPages + }; } /// @@ -71,6 +117,7 @@ internal sealed class UserRepository : IUserRepository .ThenInclude(userPermission => userPermission.Permission) .Include(user => user.UserRole!.Role.RolePermissions) .ThenInclude(rolePermission => rolePermission.Permission) + .AsSplitQuery() .FirstOrDefaultAsync(user => user.Username == username, cancellationToken) .ConfigureAwait(false); } @@ -90,35 +137,35 @@ internal sealed class UserRepository : IUserRepository .ThenInclude(userPermission => userPermission.Permission) .Include(user => user.UserRole!.Role.RolePermissions) .ThenInclude(rolePermission => rolePermission.Permission) + .AsSplitQuery() .FirstOrDefaultAsync(user => user.Username == data.Username, cancellationToken) .ConfigureAwait(false); if (foundUser is null) return Errors.Users.UserDoesNotExist; - // update scalar properties - _luminaDbContext.Entry(foundUser).CurrentValues.SetValues(data); + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundUser, data); - // update user permissions - List existingPermissions = [.. foundUser.UserPermissions]; - foreach (UserPermissionEntity permission in existingPermissions) - _luminaDbContext.UserPermissions.Remove(permission); - - foreach (UserPermissionEntity permission in data.UserPermissions) - { - _luminaDbContext.UserPermissions.Add(new UserPermissionEntity + // A permission participation is matched by its permission. Matched participations keep their identity and their audit columns, so a permission + // that is referenced elsewhere is never deleted and re-inserted just because another field of the user was edited. + CollectionReconciler.Reconcile( + foundUser.UserPermissions, + data.UserPermissions, + existingUserPermission => existingUserPermission.PermissionId, + incomingUserPermission => incomingUserPermission.PermissionId, + shouldReplace: (existingUserPermission, incomingUserPermission) => false, + createNew: incomingUserPermission => new UserPermissionEntity { UserId = foundUser.Id, - PermissionId = permission.PermissionId, - Permission = permission.Permission, + PermissionId = incomingUserPermission.PermissionId, + Permission = incomingUserPermission.Permission, User = foundUser }); - } - // update user role + // Update user role. if (foundUser.UserRole != null) _luminaDbContext.UserRoles.Remove(foundUser.UserRole); if (data.UserRole is not null) - { _luminaDbContext.UserRoles.Add(new UserRoleEntity { UserId = foundUser.Id, @@ -126,7 +173,6 @@ internal sealed class UserRepository : IUserRepository Role = data.UserRole.Role, User = foundUser }); - } return Result.Updated; } @@ -136,16 +182,21 @@ internal sealed class UserRepository : IUserRepository /// The id of the user to get. /// Cancellation token that can be used to stop the execution. /// An containing either a identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.Users - .Include(user => user.Libraries) - .ThenInclude(library => library.ContentLocations) - .Include(user => user.UserPermissions) - .ThenInclude(userPermission => userPermission.Permission) - .Include(user => user.UserRole!.Role.RolePermissions) - .ThenInclude(rolePermission => rolePermission.Permission) - .FirstOrDefaultAsync(user => user.Id == id, cancellationToken) + IQueryable query = _luminaDbContext.Users; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query + .Include(user => user.Libraries) + .ThenInclude(library => library.ContentLocations) + .Include(user => user.UserPermissions) + .ThenInclude(userPermission => userPermission.Permission) + .Include(user => user.UserRole!.Role.RolePermissions) + .ThenInclude(rolePermission => rolePermission.Permission) + .AsSplitQuery(); + return await query.FirstOrDefaultAsync(user => user.Id == id, cancellationToken) .ConfigureAwait(false); } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs index 03094365..b540ce1c 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Users/UserSettingsRepository.cs @@ -1,11 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.DataAccess.Common.Persistence; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using System; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -36,8 +38,8 @@ internal sealed class UserSettingsRepository : IUserSettingsRepository /// An representing either a successful operation, or an error. public async Task> InsertAsync(UserSettingsEntity data, CancellationToken cancellationToken) { - bool settingsExists = await _luminaDbContext.UserSettings.AnyAsync(settings => settings.UserId == data.UserId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (settingsExists) + bool doesSettingsExist = await _luminaDbContext.UserSettings.AnyAsync(settings => settings.UserId == data.UserId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesSettingsExist) return Errors.UserSettings.UserSettingsAlreadyExists; _luminaDbContext.UserSettings.Add(data); @@ -50,10 +52,12 @@ internal sealed class UserSettingsRepository : IUserSettingsRepository /// The Id of the user settings to get. /// Cancellation token that can be used to stop the execution. /// An containing either the identified by , or an error. - public async Task> GetByIdAsync(Guid id, CancellationToken cancellationToken) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { - return await _luminaDbContext.UserSettings - .FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken) + IQueryable query = _luminaDbContext.UserSettings; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + return await query.FirstOrDefaultAsync(settings => settings.Id == id, cancellationToken) .ConfigureAwait(false); } @@ -84,7 +88,8 @@ internal sealed class UserSettingsRepository : IUserSettingsRepository if (foundSettings is null) return Errors.UserSettings.UserSettingsNotFound; - _luminaDbContext.Entry(foundSettings).CurrentValues.SetValues(data); + // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor. + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundSettings, data); return Result.Updated; } } diff --git a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs index f37fceba..c49fa627 100644 --- a/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs +++ b/src/Lumina.DataAccess/Core/Seed/DataSeedService.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Domain.Common.Primitives; @@ -58,7 +60,9 @@ public class DataSeedService : IDataSeedService if (insertPermissionResult.IsFailure) return insertPermissionResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -81,7 +85,9 @@ public class DataSeedService : IDataSeedService if (insertRoleResult.IsFailure) return insertRoleResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -102,12 +108,12 @@ public class DataSeedService : IDataSeedService return Errors.Authorization.AdminAccountNotFound; // Get all permissions. - Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getPermissionsResult.IsFailure) return getPermissionsResult.Errors; // Add each permission to the admin role. - foreach (PermissionEntity permission in getPermissionsResult.Value) + foreach (PermissionEntity permission in getPermissionsResult.Value.Data) { RolePermissionEntity rolePermissionEntity = new() { @@ -122,7 +128,9 @@ public class DataSeedService : IDataSeedService if (insertRolePermissionResult.IsFailure) return insertRolePermissionResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -143,7 +151,7 @@ public class DataSeedService : IDataSeedService return Errors.Authorization.AdminRoleNotFound; // Get admin user. - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -164,7 +172,9 @@ public class DataSeedService : IDataSeedService if (insertUserRoleResult.IsFailure) return insertUserRoleResult.Errors; - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } @@ -196,7 +206,9 @@ public class DataSeedService : IDataSeedService if (insertScheduledJobResult.IsFailure) return insertScheduledJobResult.Errors; } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; return Result.Created; } diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index eb1f811e..f84beb77 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.Scheduling; @@ -20,6 +21,9 @@ namespace Lumina.DataAccess.Core.UoW; public class LuminaDbContext : DbContext { public virtual DbSet Books { get; set; } = null!; + public virtual DbSet Artists { get; set; } = null!; + public virtual DbSet Albums { get; set; } = null!; + public virtual DbSet Tracks { 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 e432f7be..a4064637 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -1,21 +1,27 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Books; +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.MusicLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Errors; using Lumina.DataAccess.Core.Repositories.Authorization; -using Lumina.DataAccess.Core.Repositories.Books; +using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.Repositories.MediaContributors; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.Repositories.Themes; using Lumina.DataAccess.Core.Repositories.Users; +using Lumina.Domain.Common.Primitives; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using System; using System.Threading; @@ -37,6 +43,9 @@ public class UnitOfWork : IUnitOfWork, IDisposable private IRoleRepository? _roleRepository; private IUserRoleRepository? _userRoleRepository; private IBookRepository? _bookRepository; + private IArtistRepository? _artistRepository; + private IAlbumRepository? _albumRepository; + private ITrackRepository? _trackRepository; private IMediaContributorRepository? _mediaContributorRepository; private IDirectoryScanFingerprintRepository? _directoryScanFingerprintRepository; private ILibraryRepository? _libraryRepository; @@ -114,6 +123,42 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the artist repository. + /// + public IArtistRepository ArtistRepository + { + get + { + _artistRepository ??= new ArtistRepository(_luminaDbContext, AlbumRepository, TrackRepository); + return _artistRepository; + } + } + + /// + /// Gets the album repository. + /// + public IAlbumRepository AlbumRepository + { + get + { + _albumRepository ??= new AlbumRepository(_luminaDbContext, TrackRepository); + return _albumRepository; + } + } + + /// + /// Gets the track repository. + /// + public ITrackRepository TrackRepository + { + get + { + _trackRepository ??= new TrackRepository(_luminaDbContext); + return _trackRepository; + } + } + public IMediaContributorRepository MediaContributorRepository { get @@ -316,9 +361,33 @@ public class UnitOfWork : IUnitOfWork, IDisposable /// Saves the changes made to the database. /// /// Cancellation token that can be used to stop the execution. - public async Task SaveChangesAsync(CancellationToken cancellationToken) + /// An representing either a successful operation, or an error. + public async Task> SaveChangesAsync(CancellationToken cancellationToken) { - await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + try + { + await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } + // A unique constraint violation is an expected persistence conflict, so it is reported as a failure result instead of bubbling up + // as an unhandled exception and being turned into a generic internal server error. Any other exception is unexpected and is left + // to propagate to the centralized exception handling middleware. + catch (DbUpdateException exception) when (IsUniqueConstraintViolation(exception)) + { + return Errors.Persistence.UniqueConstraintViolation; + } + } + + /// + /// Determines whether the provided was caused by a unique constraint violation of the storage medium. + /// + /// The exception to inspect. + /// if the exception was caused by a unique constraint violation, otherwise. + private static bool IsUniqueConstraintViolation(DbUpdateException exception) + { + // SQLite reports a generic constraint failure code for several constraints, so the extended code is used to tell a unique violation apart. + return exception.InnerException is SqliteException sqliteException + && sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE } /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs new file mode 100644 index 00000000..00d63b55 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRole.cs @@ -0,0 +1,180 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; + +/// +/// Enumeration for the role of a media contributor in a media item. +/// The role is used as the key of the localized display strings of the UI, and normalizes the free-form role names +/// returned by the metadata providers, so that roles that describe the same kind of contribution, like "Author" and +/// "Writer", are never treated as distinct. +/// +[DebuggerDisplay("{ToString()}")] +public enum MediaContributorRole +{ + /// + /// The role does not fall into any of the known roles. + /// + Other, + + /// + /// The contributor wrote the media item, like a book, a movie, or a piece of music. + /// + Author, + + /// + /// The contributor translated the media item into another language. + /// + Translator, + + /// + /// The contributor created the illustrations of the media item. + /// + Illustrator, + + /// + /// The contributor published the media item. + /// + Publisher, + + /// + /// The contributor narrated the media item. + /// + Narrator, + + /// + /// The contributor played a role in a filmed media item. + /// + Actor, + + /// + /// The contributor directed a filmed media item. + /// + Director, + + /// + /// The contributor wrote the screenplay of a filmed media item. + /// + Screenwriter, + + /// + /// The contributor wrote the music of the media item. + /// + Composer, + + /// + /// The contributor wrote the lyrics of the media item. + /// + Lyricist, + + /// + /// The contributor arranged the music of the media item. + /// + Arranger, + + /// + /// The contributor conducted the ensemble performing the media item. + /// + Conductor, + + /// + /// The contributor oversaw the production of the media item. + /// + Producer, + + /// + /// The contributor oversaw the overall production of the media item, rather than a single track or episode. + /// + ExecutiveProducer, + + /// + /// The contributor operated the recording equipment during the production of the media item. + /// + Engineer, + + /// + /// The contributor mixed the audio of the media item. + /// + Mixer, + + /// + /// The contributor created a remix of the media item. + /// + Remixer, + + /// + /// The contributor released the media item under a record label. + /// + RecordLabel, + + /// + /// The contributor sang the media item. + /// + Vocals, + + /// + /// The contributor sang the backing vocals of the media item. + /// + BackingVocals, + + /// + /// The contributor played the guitar in the media item. + /// + Guitar, + + /// + /// The contributor played the bass guitar in the media item. + /// + BassGuitar, + + /// + /// The contributor played the drums in the media item. + /// + Drums, + + /// + /// The contributor played percussion in the media item. + /// + Percussion, + + /// + /// The contributor played the keyboards in the media item. + /// + Keyboards, + + /// + /// The contributor played the piano in the media item. + /// + Piano, + + /// + /// The contributor played the synthesizer in the media item. + /// + Synthesizer, + + /// + /// The contributor played a string instrument in the media item. + /// + Strings, + + /// + /// The contributor played a woodwind instrument in the media item. + /// + Woodwinds, + + /// + /// The contributor played a brass instrument in the media item. + /// + Brass, + + /// + /// The contributor sang in a choir in the media item. + /// + Choir, + + /// + /// The contributor orchestrated the music of the media item. + /// + Orchestrator +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs deleted file mode 100644 index 597b7d0c..00000000 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaContributors/MediaContributorRoleCategory.cs +++ /dev/null @@ -1,99 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; - -/// -/// Enumeration for the canonical category of the role of a media contributor in a media item. -/// The category normalizes the free-form role names returned by the metadata providers, so that roles -/// that describe the same kind of contribution, like "Author" and "Writer", are never treated as distinct. -/// -[DebuggerDisplay("{ToString()}")] -public enum MediaContributorRoleCategory -{ - /// - /// The role does not fall into any of the known categories. - /// - Other, - - /// - /// The contributor created the media item, like a book, a movie, or a piece of music. - /// - Author, - - /// - /// The contributor translated the media item into another language. - /// - Translator, - - /// - /// The contributor created the illustrations of the media item. - /// - Illustrator, - - /// - /// The contributor published the media item. - /// - Publisher, - - /// - /// The contributor narrated the media item. - /// - Narrator, - - /// - /// The contributor is credited as the artist of the media item. - /// - Artist, - - /// - /// The contributor performed the media item, whether singing or playing an instrument. - /// - Performer, - - /// - /// The contributor wrote the music of the media item. - /// - Composer, - - /// - /// The contributor wrote the lyrics of the media item. - /// - Lyricist, - - /// - /// The contributor oversaw the production of the media item. - /// - Producer, - - /// - /// The contributor operated the recording equipment during the production of the media item. - /// - Engineer, - - /// - /// The contributor conducted the ensemble performing the media item. - /// - Conductor, - - /// - /// The contributor arranged the music of the media item. - /// - Arranger, - - /// - /// The contributor mixed the audio of the media item. - /// - Mixer, - - /// - /// The contributor created a remix of the media item. - /// - Remixer, - - /// - /// The contributor released the media item under a record label. - /// - RecordLabel -} diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs index 33a9737d..8cd20fbe 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -26,6 +26,7 @@ public static partial class Errors public static Error BitrateMustBeAPositiveNumber => Error.Validation(description: nameof(BitrateMustBeAPositiveNumber)); public static Error CannotNavigateUp => Error.Failure(description: nameof(CannotNavigateUp)); public static Error NameCannotBeEmpty => Error.Validation(description: nameof(NameCannotBeEmpty)); + public static Error FileNameCannotBeEmpty => Error.Validation(description: nameof(FileNameCannotBeEmpty)); public static Error FileAlreadyExists => Error.Conflict(description: nameof(FileAlreadyExists)); public static Error DirectoryNotFound => Error.NotFound(description: nameof(DirectoryNotFound)); public static Error DirectoryAlreadyExists => Error.Conflict(description: nameof(DirectoryAlreadyExists)); diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index ee185d0c..87d4bf7b 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -11,7 +11,6 @@ public static partial class Errors { public static class MediaContributor { - public static Error ContributorsListCannotBeNull => Error.Validation(description: nameof(ContributorsListCannotBeNull)); public static Error ContributorNameCannotBeEmpty => Error.Validation(description: nameof(ContributorNameCannotBeEmpty)); public static Error ContributorDisplayNameCannotBeEmpty => Error.Validation(description: nameof(ContributorDisplayNameCannotBeEmpty)); public static Error ContributorDisplayNameMustBeMaximum100CharactersLong => Error.Validation(description: nameof(ContributorDisplayNameMustBeMaximum100CharactersLong)); @@ -20,5 +19,9 @@ public static partial class Errors public static Error RoleNameMustBeMaximum50CharactersLong => Error.Validation(description: nameof(RoleNameMustBeMaximum50CharactersLong)); public static Error RoleCategoryCannotBeEmpty => Error.Validation(description: nameof(RoleCategoryCannotBeEmpty)); public static Error ContributorRoleCannotBeNull => Error.Validation(description: nameof(ContributorRoleCannotBeNull)); + 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 UnknownMediaContributorRole => Error.Validation(description: nameof(UnknownMediaContributorRole)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs b/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs index c1440d63..26a0d1cf 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Metadata.cs @@ -42,6 +42,5 @@ public static partial class Errors public static Error RatingValueCannotBeGreaterThanMaxValue => Error.Validation(description: nameof(RatingValueCannotBeGreaterThanMaxValue)); public static Error RatingVoteCountMustBePositive => Error.Validation(description: nameof(RatingVoteCountMustBePositive)); public static Error RatingsListCannotBeNull => Error.Validation(description: nameof(RatingsListCannotBeNull)); - public static Error InvalidIsoCode => Error.Validation(description: nameof(InvalidIsoCode)); } } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Music.cs b/src/Lumina.Domain/Common/Errors/Errors.Music.cs index 8564c459..42acfa31 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Music.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Music.cs @@ -11,13 +11,43 @@ public static partial class Errors { public static class Music { + public static Error ArtistNotFound => Error.NotFound(description: nameof(ArtistNotFound)); + public static Error ArtistAlreadyExists => Error.Conflict(description: nameof(ArtistAlreadyExists)); + public static Error ArtistIdCannotBeEmpty => Error.Validation(description: nameof(ArtistIdCannotBeEmpty)); public static Error ArtistNameCannotBeEmpty => Error.Validation(description: nameof(ArtistNameCannotBeEmpty)); + public static Error ArtistNameMustBeMaximum255CharactersLong => Error.Validation(description: nameof(ArtistNameMustBeMaximum255CharactersLong)); + public static Error ArtistWebsiteMustBeMaximum2048CharactersLong => Error.Validation(description: nameof(ArtistWebsiteMustBeMaximum2048CharactersLong)); public static Error MusicBrainzIdInvalidFormat => Error.Validation(description: nameof(MusicBrainzIdInvalidFormat)); public static Error IsrcValueCannotBeEmpty => Error.Validation(description: nameof(IsrcValueCannotBeEmpty)); public static Error IsrcInvalidFormat => Error.Validation(description: nameof(IsrcInvalidFormat)); public static Error BarcodeValueCannotBeEmpty => Error.Validation(description: nameof(BarcodeValueCannotBeEmpty)); public static Error InvalidFormatForBarcode => Error.Validation(description: nameof(InvalidFormatForBarcode)); - public static Error CreditRoleDisplayNameCannotBeEmpty => Error.Validation(description: nameof(CreditRoleDisplayNameCannotBeEmpty)); + public static Error AlbumNotFound => Error.NotFound(description: nameof(AlbumNotFound)); + public static Error AlbumAlreadyExists => Error.Conflict(description: nameof(AlbumAlreadyExists)); + public static Error ArtistMustHaveAtLeastOneAlbum => Error.Forbidden(description: nameof(ArtistMustHaveAtLeastOneAlbum)); + public static Error AlbumIdCannotBeEmpty => Error.Validation(description: nameof(AlbumIdCannotBeEmpty)); + public static Error AlbumsListCannotBeNull => Error.Validation(description: nameof(AlbumsListCannotBeNull)); + public static Error AlbumTitleCannotBeEmpty => Error.Validation(description: nameof(AlbumTitleCannotBeEmpty)); + public static Error AlbumTitleMustBeMaximum255CharactersLong => Error.Validation(description: nameof(AlbumTitleMustBeMaximum255CharactersLong)); + public static Error TotalDiscsMustBeGreaterThanZero => Error.Validation(description: nameof(TotalDiscsMustBeGreaterThanZero)); + public static Error TotalTracksMustBeGreaterThanZero => Error.Validation(description: nameof(TotalTracksMustBeGreaterThanZero)); + 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 UnknownMusicKey => Error.Validation(description: nameof(UnknownMusicKey)); + public static Error CatalogNumberMustBeMaximum50CharactersLong => Error.Validation(description: nameof(CatalogNumberMustBeMaximum50CharactersLong)); + public static Error TrackNotFound => Error.NotFound(description: nameof(TrackNotFound)); + public static Error TrackAlreadyExists => Error.Conflict(description: nameof(TrackAlreadyExists)); + public static Error TrackIdCannotBeEmpty => Error.Validation(description: nameof(TrackIdCannotBeEmpty)); + public static Error TracksListCannotBeNull => Error.Validation(description: nameof(TracksListCannotBeNull)); + public static Error TrackPathCannotBeEmpty => Error.Validation(description: nameof(TrackPathCannotBeEmpty)); + public static Error TrackPathMustBeMaximum2048CharactersLong => Error.Validation(description: nameof(TrackPathMustBeMaximum2048CharactersLong)); + public static Error TrackPathMustBeWithinLibraryContentLocations => Error.Validation(description: nameof(TrackPathMustBeWithinLibraryContentLocations)); + public static Error TrackNumberMustBeGreaterThanZero => Error.Validation(description: nameof(TrackNumberMustBeGreaterThanZero)); + public static Error DiscNumberMustBeGreaterThanZero => Error.Validation(description: nameof(DiscNumberMustBeGreaterThanZero)); + public static Error ScriptMustBeMaximum50CharactersLong => Error.Validation(description: nameof(ScriptMustBeMaximum50CharactersLong)); + public static Error WorkMustBeMaximum255CharactersLong => Error.Validation(description: nameof(WorkMustBeMaximum255CharactersLong)); + public static Error BpmMustBeGreaterThanZero => Error.Validation(description: nameof(BpmMustBeGreaterThanZero)); public static Error TheArtistAlreadyHasTheAlbum => Error.Forbidden(description: nameof(TheArtistAlreadyHasTheAlbum)); public static Error TheArtistDoesNotHaveTheAlbum => Error.Forbidden(description: nameof(TheArtistDoesNotHaveTheAlbum)); public static Error TheTrackIsAlreadyInTheAlbum => Error.Forbidden(description: nameof(TheTrackIsAlreadyInTheAlbum)); diff --git a/src/Lumina.Domain/Common/Errors/Errors.Reading.cs b/src/Lumina.Domain/Common/Errors/Errors.Reading.cs index 271bfe9d..ebe6790b 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Reading.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Reading.cs @@ -11,7 +11,6 @@ public static partial class Errors { public static class Reading { - public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty)); public static Error LocationRefCannotBeEmpty => Error.Validation(description: nameof(LocationRefCannotBeEmpty)); public static Error ResourceKeyCannotBeEmpty => Error.Validation(description: nameof(ResourceKeyCannotBeEmpty)); public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound)); diff --git a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs index a31b8da5..ad7eff46 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.WrittenContent.cs @@ -37,6 +37,8 @@ public static partial class Errors public static Error VolumeNumberMustBeGreaterThanZero => Error.Validation(description: nameof(VolumeNumberMustBeGreaterThanZero)); public static Error BookLibraryCannotBeNull => Error.Validation(description: nameof(BookLibraryCannotBeNull)); public static Error BookPathCannotBeEmpty => Error.Validation(description: nameof(BookPathCannotBeEmpty)); + public static Error BookPathMustBeMaximum2048CharactersLong => Error.Validation(description: nameof(BookPathMustBeMaximum2048CharactersLong)); + public static Error BookPathMustBeWithinLibraryContentLocations => Error.Validation(description: nameof(BookPathMustBeWithinLibraryContentLocations)); public static Error BookIdCannotBeEmpty => Error.Validation(description: nameof(BookIdCannotBeEmpty)); public static Error BookCoverCannotBeNull => Error.Validation(description: nameof(BookCoverCannotBeNull)); public static Error BookNotFound => Error.NotFound(description: nameof(BookNotFound)); diff --git a/src/Lumina.Domain/Common/Models/Core/Entity.cs b/src/Lumina.Domain/Common/Models/Core/Entity.cs index e100c991..e381af5f 100644 --- a/src/Lumina.Domain/Common/Models/Core/Entity.cs +++ b/src/Lumina.Domain/Common/Models/Core/Entity.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using System; #endregion @@ -21,9 +22,9 @@ public abstract class Entity : IEquatable> where TId : notnull public DateTime CreatedOnUtc { get; set; } /// - /// Gets the date and time when the entity was last updated. + /// Gets the date and time when the entity was last updated, if applicable. /// - public DateTime? UpdatedOnUtc { get; set; } + public Optional UpdatedOnUtc { get; set; } /// /// Initializes a new instance of the class. diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs index 6c3fa5a3..27323e54 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/BaseMetadata.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using System; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -68,7 +67,6 @@ public abstract class BaseMetadata : ValueObject /// The list of tags of the element to which this metadata object belongs to. /// The optional language of the element to which this metadata object belongs to, if applicable. /// The optional original language of the element to which this metadata object belongs to, if applicable. - /// Thrown when the value is protected BaseMetadata( string title, Optional originalTitle, @@ -79,7 +77,7 @@ public abstract class BaseMetadata : ValueObject Optional language, Optional originalLanguage) { - Title = title ?? throw new ArgumentNullException(nameof(title)); + Title = title; OriginalTitle = originalTitle; Description = description; ReleaseInfo = releaseInfo; diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs index 3747dbe1..b95ca9e8 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Genre.cs @@ -34,7 +34,7 @@ public class Genre : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static Result Create(string? name) + public static Result Create(string name) { if (string.IsNullOrWhiteSpace(name)) return Errors.Errors.Metadata.GenreNameCannotBeEmpty; diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs index c0231804..7420583b 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/LanguageInfo.cs @@ -2,7 +2,6 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Common.Errors; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -49,17 +48,9 @@ public class LanguageInfo : ValueObject /// The ISO 639-1 two-letter language code. /// The full name of the language in English. /// The optional native name of the language. - /// - /// An containing either a successfully created , or an error message. - /// - public static Result Create(string? languageCode, string? languageName, Optional nativeName) + /// The created . + public static LanguageInfo Create(string languageCode, string languageName, Optional nativeName) { - if (string.IsNullOrWhiteSpace(languageCode)) - return Errors.Errors.Metadata.LanguageCodeCannotBeEmpty; - if (string.IsNullOrWhiteSpace(languageName)) - return Errors.Errors.Metadata.LanguageNameCannotBeEmpty; - if (languageCode.Length != 2) - return Errors.Errors.Metadata.InvalidIsoCode; return new LanguageInfo(languageCode, languageName, nativeName); } diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Mood.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Mood.cs index 01c38c57..777527ea 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Mood.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Mood.cs @@ -35,7 +35,7 @@ public class Mood : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static Result Create(string? name) + public static Result Create(string name) { if (string.IsNullOrWhiteSpace(name)) return Errors.Errors.Metadata.MoodNameCannotBeEmpty; diff --git a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs index 44b4280e..c55a60b0 100644 --- a/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs +++ b/src/Lumina.Domain/Common/ValueObjects/Metadata/Tag.cs @@ -35,7 +35,7 @@ public class Tag : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static Result Create(string? name) + public static Result Create(string name) { if (string.IsNullOrWhiteSpace(name)) return Errors.Errors.Metadata.TagNameCannotBeEmpty; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRating.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRating.cs index 212f5505..fbd014ee 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRating.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRating.cs @@ -45,6 +45,8 @@ public class AudioRating : Rating /// public static Result Create(decimal value, decimal maxValue, Optional source, Optional voteCount) { + if (maxValue < 0 || value < 0) + return Errors.Metadata.RatingValueMustBePositive; if (value > maxValue) return Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs index f9227955..ea66a780 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs @@ -2,12 +2,16 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +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.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; #endregion namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; @@ -16,16 +20,23 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib /// Aggregate root for an artist. /// /// -/// An artist is the entity that produced a musical work, whatever or whoever that might be. An artist is a single person, like Freddie Mercury, a group of people, -/// like Queen, or a collaboration between artists, like Queen and David Bowie. The media contributors that make up the artist, together with the roles they play, -/// are tracked as credits, and the artist can also reference the single media contributor it corresponds to, so that an artist and the person behind it are never duplicated. +/// An artist is the entity that produced a musical work, whatever or whoever that might be. An artist is a single person, like Freddie Mercury, a group of people, +/// like Queen, or a collaboration between artists, like Queen and David Bowie. The media contributors that make up the artist, together with the roles they play, +/// are tracked as contributors. +/// The albums of the artist, and the tracks of those albums, are entities inside this aggregate, not aggregate roots, so they are referenced by object, as DDD prescribes +/// for entities within the same consistency boundary. The methods that mutate them therefore take the album, respectively the track, itself, rather than its id. /// [DebuggerDisplay("Id: {Id} Name: {Name}")] public sealed class Artist : AggregateRoot { - private readonly List _credits; + private readonly HashSet _contributors; private readonly List _albums; + /// + /// Gets the Id of the media library this artist belongs to. + /// + public LibraryId LibraryId { get; private set; } + /// /// Gets the name of the artist. /// @@ -42,14 +53,9 @@ public sealed class Artist : AggregateRoot public Optional MusicBrainzArtistId { get; private set; } /// - /// Gets the Id of the media contributor the artist corresponds to, if applicable. + /// Gets the list of the media contributors that make up the artist. /// - public Optional MediaContributorId { get; private set; } - - /// - /// Gets the list of the credits of the media contributors that make up the artist. - /// - public IReadOnlyCollection Credits => _credits.AsReadOnly(); + public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); /// /// Gets the list of albums of the artist. @@ -60,68 +66,70 @@ public sealed class Artist : AggregateRoot /// Initializes a new instance of the class. /// /// 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 website of the artist. /// The optional MusicBrainz identifier of the artist. - /// The optional Id of the media contributor the artist corresponds to. - /// The list of the credits of the media contributors that make up 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. /// The date and time when the entity was last updated. private Artist( ArtistId id, + LibraryId libraryId, string name, Optional website, Optional musicBrainzArtistId, - Optional mediaContributorId, - List credits, + List contributors, List albums, DateTime createdOnUtc, Optional updatedOnUtc) : base(id) { Id = id; + LibraryId = libraryId; Name = name; Website = website; MusicBrainzArtistId = musicBrainzArtistId; - MediaContributorId = mediaContributorId; - _credits = credits; + _contributors = [.. contributors]; _albums = albums; CreatedOnUtc = createdOnUtc; - UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null; + UpdatedOnUtc = updatedOnUtc; } /// /// Creates a new instance of the class. /// + /// The Id of the media library this artist belongs to. /// The name of the artist. /// The optional website of the artist. /// The optional MusicBrainz identifier of the artist. - /// The optional Id of the media contributor the artist corresponds to. - /// The list of the credits of the media contributors that make up the artist. + /// The list of the media contributors that make up the artist. /// The list of albums of the artist. /// /// An containing either a successfully created , or an error message. /// public static Result Create( + LibraryId libraryId, string name, Optional website, Optional musicBrainzArtistId, - Optional mediaContributorId, - List credits, + List contributors, List albums) { if (string.IsNullOrWhiteSpace(name)) return Errors.Music.ArtistNameCannotBeEmpty; + if (albums.Count is 0) + return Errors.Music.ArtistMustHaveAtLeastOneAlbum; return new Artist( ArtistId.CreateUnique(), + libraryId, name, website, musicBrainzArtistId, - mediaContributorId, - credits, + contributors, albums, - DateTime.UtcNow, + DateTime.UtcNow, // TODO: should be IDateTimeProvider. Optional.None()); } @@ -129,11 +137,11 @@ public sealed class Artist : AggregateRoot /// Creates a new instance of the class, with a pre-existing . /// /// 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 website of the artist. /// The optional MusicBrainz identifier of the artist. - /// The optional Id of the media contributor the artist corresponds to. - /// The list of the credits of the media contributors that make up 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. /// The date and time when the entity was last updated. @@ -142,25 +150,27 @@ public sealed class Artist : AggregateRoot /// public static Result Create( ArtistId id, + LibraryId libraryId, string name, Optional website, Optional musicBrainzArtistId, - Optional mediaContributorId, - List credits, + List contributors, List albums, DateTime createdOnUtc, Optional updatedOnUtc) { if (string.IsNullOrWhiteSpace(name)) return Errors.Music.ArtistNameCannotBeEmpty; + if (albums.Count is 0) + return Errors.Music.ArtistMustHaveAtLeastOneAlbum; return new Artist( id, + libraryId, name, website, musicBrainzArtistId, - mediaContributorId, - credits, + contributors, albums, createdOnUtc, updatedOnUtc); @@ -188,18 +198,200 @@ public sealed class Artist : AggregateRoot { if (!_albums.Contains(album)) return Errors.Music.TheArtistDoesNotHaveTheAlbum; + if (_albums.Count is 1) + return Errors.Music.ArtistMustHaveAtLeastOneAlbum; _albums.Remove(album); return Result.Deleted; } /// - /// Replaces the credits of the media contributors that make up the artist with the provided . + /// Replaces the media contributors that make up the artist with the provided . /// - /// The credits of the media contributors that make up the artist. - public void UpdateCredits(IReadOnlyCollection credits) + /// The media contributors that make up the artist. + public void UpdateContributors(IReadOnlyCollection contributors) { - // replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate - _credits.Clear(); - _credits.AddRange(credits); + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. + _contributors.Clear(); + _contributors.UnionWith(contributors); + } + + /// + /// Updates the details of the artist, without touching the albums and the media contributors. + /// + /// The name of the artist. + /// 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 website, + Optional musicBrainzArtistId) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.Music.ArtistNameCannotBeEmpty; + + Name = name; + Website = website; + MusicBrainzArtistId = musicBrainzArtistId; + UpdatedOnUtc = Optional.Some(DateTime.UtcNow); + return Result.Updated; + } + + /// + /// Updates an album of the artist, together with its media contributors and ratings, without touching its tracks. + /// + /// + /// An album is a child entity of the artist aggregate, not an aggregate root, so it is mutated through its owning artist, + /// which is the consistency boundary. Book is itself an aggregate root, so its update flow reconstitutes it directly + /// with its own Create method instead. This difference is intentional. + /// + /// The album to update. + /// The album metadata of the album. + /// The optional physical or digital medium of the album. + /// The optional barcode of the album. + /// The optional catalog number 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. + /// The media contributors of the album. + /// The ratings of the album. + /// An representing either a successful operation, or an error. + public Result UpdateAlbum( + Album album, + AlbumMetadata metadata, + Optional mediaFormat, + Optional barcode, + Optional catalogNumber, + Optional musicBrainzReleaseId, + Optional musicBrainzReleaseGroupId, + Optional musicBrainzReleaseArtistId, + IReadOnlyCollection contributors, + IReadOnlyCollection ratings) + { + // The album is an entity inside this aggregate, referenced by object, so it must be one of the albums of the artist. + if (!_albums.Contains(album)) + return Errors.Music.AlbumNotFound; + + album.UpdateDetails(metadata, mediaFormat, barcode, catalogNumber, musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId); + album.UpdateContributors(contributors); + album.UpdateRatings(ratings); + UpdatedOnUtc = Optional.Some(DateTime.UtcNow); + return Result.Updated; + } + + /// + /// Updates a track of an album of the artist, together with its media contributors, ratings, moods and ISRCs. + /// + /// + /// A track is a child entity of the artist aggregate, not an aggregate root, so it is mutated through its owning artist, + /// which is the consistency boundary. Book is itself an aggregate root, so its update flow reconstitutes it directly + /// with its own Create method instead. This difference is intentional. + /// + /// The album the track belongs to. + /// The track to update. + /// The file system path of the track. + /// The audio metadata of the track. + /// The number of the track on its disc. + /// The optional number of the disc the track belongs to. + /// 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. + /// 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. + /// The ratings of the track. + /// An representing either a successful operation, or an error. + public Result UpdateTrackInAlbum( + Album album, + Track track, + string path, + AudioMetadata metadata, + int trackNumber, + Optional discNumber, + Optional script, + Optional key, + Optional bpm, + Optional work, + Optional musicBrainzRecordingId, + Optional musicBrainzTrackId, + Optional musicBrainzWorkId, + IReadOnlyCollection moods, + IReadOnlyCollection isrcs, + IReadOnlyCollection contributors, + IReadOnlyCollection ratings) + { + // The album and the track are entities inside this aggregate, referenced by object, so they must belong to the artist, respectively to the album. + if (!_albums.Contains(album)) + return Errors.Music.AlbumNotFound; + if (!album.Tracks.Contains(track)) + return Errors.Music.TrackNotFound; + + track.UpdateDetails( + path, + metadata, + trackNumber, + discNumber, + script, + key, + bpm, + work, + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId); + track.UpdateMoods(moods); + track.UpdateIsrcs(isrcs); + track.UpdateContributors(contributors); + track.UpdateRatings(ratings); + UpdatedOnUtc = Optional.Some(DateTime.UtcNow); + return Result.Updated; + } + + /// + /// Adds a track to an album of the artist. + /// + /// The album the track is added to. + /// The track to be added. + /// An representing either a successful operation, or an error. + /// + /// A track is a child entity of the artist aggregate, not an aggregate root, so it is added through its owning artist, + /// which is the consistency boundary. Book and Artist are themselves aggregate roots, so they are created directly instead. + /// This difference is intentional. + /// + public Result AddTrackToAlbum(Album album, Track track) + { + // The album is an entity inside this aggregate, referenced by object, so it must be one of the albums of the artist. + if (!_albums.Contains(album)) + return Errors.Music.AlbumNotFound; + + Result addResult = album.AddTrack(track); + if (addResult.IsFailure) + return addResult.Errors; + + return Result.Created; + } + + /// + /// Removes a track from an album of the artist. + /// + /// The album the track is removed from. + /// The track to remove. + /// An representing either a successful operation, or an error. + /// + /// A track is a child entity of the artist aggregate, not an aggregate root, so it is removed through its owning artist, + /// which is the consistency boundary. This difference is intentional. + /// + public Result RemoveTrackFromAlbum(Album album, Track track) + { + // The album and the track are entities inside this aggregate, referenced by object, so they must belong to the artist, respectively to the album. + if (!_albums.Contains(album)) + return Errors.Music.AlbumNotFound; + if (!album.Tracks.Contains(track)) + return Errors.Music.TrackNotFound; + + return album.RemoveTrack(track); } } 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 3008b344..665f7cfd 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Album.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Album.cs @@ -5,6 +5,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -17,7 +18,7 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib [DebuggerDisplay("{Id}: {Metadata.Title}")] public sealed class Album : Entity { - private readonly List _credits; + private readonly List _contributors; private readonly List _ratings; private readonly List _tracks; @@ -57,9 +58,9 @@ public sealed class Album : Entity public Optional MusicBrainzReleaseArtistId { get; private set; } /// - /// Gets the list of the credits of the media contributors of the album. + /// Gets the list of the media contributors of the album. /// - public IReadOnlyCollection Credits => _credits.AsReadOnly(); + public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); /// /// Gets the list of ratings for this album. @@ -82,9 +83,11 @@ public sealed class Album : Entity /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. - /// The list of the credits of the media contributors of the album. + /// The list of the media contributors of the album. /// The list of ratings for the album. /// The list of tracks of the album. + /// The date and time when the entity was created. + /// The date and time when the entity was last updated. private Album( AlbumId id, AlbumMetadata metadata, @@ -94,9 +97,11 @@ public sealed class Album : Entity Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, - List credits, + List contributors, List ratings, - List tracks) : base(id) + List tracks, + DateTime createdOnUtc, + Optional updatedOnUtc) : base(id) { Id = id; Metadata = metadata; @@ -106,9 +111,11 @@ public sealed class Album : Entity MusicBrainzReleaseId = musicBrainzReleaseId; MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId; MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId; - _credits = credits; + _contributors = contributors; _ratings = ratings; _tracks = tracks; + CreatedOnUtc = createdOnUtc; + UpdatedOnUtc = updatedOnUtc; } /// @@ -121,7 +128,7 @@ public sealed class Album : Entity /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. - /// The list of the credits of the media contributors of the album. + /// The list of the media contributors of the album. /// The list of ratings for the album. /// The list of tracks of the album. /// @@ -135,7 +142,7 @@ public sealed class Album : Entity Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, - List credits, + List contributors, List ratings, List tracks) { @@ -148,9 +155,11 @@ public sealed class Album : Entity musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, - credits, + contributors, ratings, - tracks); + tracks, + DateTime.UtcNow, // TODO: should be IDateTimeProvider + Optional.None()); } /// @@ -164,9 +173,11 @@ public sealed class Album : Entity /// The optional MusicBrainz identifier of the release. /// The optional MusicBrainz identifier of the release group. /// The optional MusicBrainz identifier of the release artist. - /// The list of the credits of the media contributors of the album. + /// The list of the media contributors of the album. /// The list of ratings for the album. /// The list of tracks of the album. + /// The date and time when the entity was created. + /// The date and time when the entity was last updated. /// /// An containing either a successfully created , or an error message. /// @@ -179,9 +190,11 @@ public sealed class Album : Entity Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, - List credits, + List contributors, List ratings, - List tracks) + List tracks, + DateTime createdOnUtc, + Optional updatedOnUtc) { return new Album( id, @@ -192,9 +205,11 @@ public sealed class Album : Entity musicBrainzReleaseId, musicBrainzReleaseGroupId, musicBrainzReleaseArtistId, - credits, + contributors, ratings, - tracks); + tracks, + createdOnUtc, + updatedOnUtc); } /// @@ -202,7 +217,7 @@ public sealed class Album : Entity /// /// The track to be added. /// An representing either a successful operation, or an error. - public Result AddTrack(Track track) + internal Result AddTrack(Track track) { if (_tracks.Contains(track)) return Errors.Music.TheTrackIsAlreadyInTheAlbum; @@ -215,7 +230,7 @@ public sealed class Album : Entity /// /// The track to be removed. /// An representing either a successful operation, or an error. - public Result RemoveTrack(Track track) + internal Result RemoveTrack(Track track) { if (!_tracks.Contains(track)) return Errors.Music.TheTrackIsNotInTheAlbum; @@ -224,13 +239,55 @@ public sealed class Album : Entity } /// - /// Replaces the credits of the media contributors of the album with the provided . + /// Replaces the media contributors of the album with the provided . /// - /// The credits of the media contributors of the album. - public void UpdateCredits(IReadOnlyCollection credits) + /// The media contributors of the album. + internal void UpdateContributors(IReadOnlyCollection contributors) { // replace the contents of the collection in place, preserving the readonly reference invariants of the entity - _credits.Clear(); - _credits.AddRange(credits); + _contributors.Clear(); + _contributors.AddRange(contributors); + } + + /// + /// Replaces the ratings of the album with the provided . + /// + /// The ratings of the album. + internal void UpdateRatings(IReadOnlyCollection ratings) + { + // replace the contents of the collection in place, preserving the readonly reference invariants of the entity + _ratings.Clear(); + _ratings.AddRange(ratings); + } + + /// + /// Updates the details of the album, without touching the ratings, the media contributors, and the tracks. + /// + /// The album metadata of the album. + /// The optional physical or digital medium of the album. + /// The optional barcode of the album. + /// The optional catalog number 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 mediaFormat, + Optional barcode, + Optional catalogNumber, + Optional musicBrainzReleaseId, + Optional musicBrainzReleaseGroupId, + Optional musicBrainzReleaseArtistId) + { + Metadata = metadata; + MediaFormat = mediaFormat; + Barcode = barcode; + CatalogNumber = catalogNumber; + MusicBrainzReleaseId = musicBrainzReleaseId; + MusicBrainzReleaseGroupId = musicBrainzReleaseGroupId; + MusicBrainzReleaseArtistId = musicBrainzReleaseArtistId; + UpdatedOnUtc = Optional.Some(DateTime.UtcNow); + return Result.Updated; } } 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 ca77eb72..d7c418b8 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/Track.cs @@ -6,6 +6,7 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.Value using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -18,16 +19,11 @@ namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLib [DebuggerDisplay("{Id}: {Metadata.Title}")] public sealed class Track : Entity { - private readonly List _isrcs; private readonly List _moods; - private readonly List _credits; + private readonly List _isrcs; + private readonly List _contributors; private readonly List _ratings; - /// - /// Gets the Id of the media library this track belongs to. - /// - public LibraryId LibraryId { get; private set; } - /// /// Gets the file system path of the track. /// @@ -94,9 +90,9 @@ public sealed class Track : Entity public IReadOnlyCollection Isrcs => _isrcs.AsReadOnly(); /// - /// Gets the list of the credits of the media contributors of the track. + /// Gets the list of the media contributors of the track. /// - public IReadOnlyCollection Credits => _credits.AsReadOnly(); + public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); /// /// Gets the list of ratings for this track. @@ -107,49 +103,50 @@ public sealed class Track : Entity /// Initializes a new instance of the class. /// /// The object representing the unique identifier of the track. - /// The Id of the media library this track belongs to. /// The file system path of the track. /// The audio metadata of the track. /// The number of the track on its disc. /// The optional number of the disc the track belongs to. - /// The list of ISRC of the track. + /// 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. - /// The list of moods of the track. + /// The list of ISRC of the track. /// The optional title of the 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 credits of the media contributors of the track. + /// The list of the media contributors of the track. /// The list of ratings for 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, - LibraryId libraryId, string path, AudioMetadata metadata, int trackNumber, Optional discNumber, - List isrcs, + List moods, Optional script, Optional key, Optional bpm, - List moods, + List isrcs, Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, - List ratings) : base(id) + List contributors, + List ratings, + DateTime createdOnUtc, + Optional updatedOnUtc) : base(id) { Id = id; - LibraryId = libraryId; Path = path; Metadata = metadata; TrackNumber = trackNumber; DiscNumber = discNumber; - _isrcs = isrcs; _moods = moods; + _isrcs = isrcs; Script = script; Key = key; Bpm = bpm; @@ -157,140 +154,220 @@ public sealed class Track : Entity MusicBrainzRecordingId = musicBrainzRecordingId; MusicBrainzTrackId = musicBrainzTrackId; MusicBrainzWorkId = musicBrainzWorkId; - _credits = credits; + _contributors = contributors; _ratings = ratings; + CreatedOnUtc = createdOnUtc; + UpdatedOnUtc = updatedOnUtc; } /// /// Creates a new instance of the class. /// - /// The Id of the media library this track belongs to. /// The file system path of the track. /// The audio metadata of the track. /// The number of the track on its disc. /// The optional number of the disc the track belongs to. - /// The list of ISRC of the track. + /// 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. - /// The list of moods of the track. + /// The list of ISRC of the track. /// The optional title of the 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 credits of the media contributors of the track. + /// The list of the media contributors of the track. /// The list of ratings for the track. /// /// An containing either a successfully created , or an error message. /// public static Result Create( - LibraryId libraryId, string path, AudioMetadata metadata, int trackNumber, Optional discNumber, - List isrcs, + List moods, Optional script, Optional key, Optional bpm, - List moods, + List isrcs, Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, + List contributors, List ratings) { return new Track( TrackId.CreateUnique(), - libraryId, path, metadata, trackNumber, discNumber, - isrcs, + moods, script, key, bpm, - moods, + isrcs, work, musicBrainzRecordingId, musicBrainzTrackId, musicBrainzWorkId, - credits, - ratings); + contributors, + ratings, + DateTime.UtcNow, // TODO: should be IDateTimeProvider + Optional.None()); } /// /// Creates a new instance of the class, with a pre-existing . /// /// The object representing the unique identifier of the track. - /// The Id of the media library this track belongs to. /// The file system path of the track. /// The audio metadata of the track. /// The number of the track on its disc. /// The optional number of the disc the track belongs to. - /// The list of ISRC of the track. + /// 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. - /// The list of moods of the track. + /// The list of ISRC of the track. /// The optional title of the 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 credits of the media contributors of the track. + /// The list of the media contributors of the track. /// The list of ratings for the track. + /// The date and time when the entity was created. + /// The date and time when the entity was last updated. /// /// An containing either a successfully created , or an error message. /// public static Result Create( TrackId id, - LibraryId libraryId, string path, AudioMetadata metadata, int trackNumber, Optional discNumber, - List isrcs, + List moods, Optional script, Optional key, Optional bpm, - List moods, + List isrcs, Optional work, Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, - List ratings) + List contributors, + List ratings, + DateTime createdOnUtc, + Optional updatedOnUtc) { return new Track( id, - libraryId, path, metadata, trackNumber, discNumber, - isrcs, + moods, script, key, bpm, - moods, + isrcs, work, musicBrainzRecordingId, musicBrainzTrackId, musicBrainzWorkId, - credits, - ratings); + contributors, + ratings, + createdOnUtc, + updatedOnUtc); } /// - /// Replaces the credits of the media contributors of the track with the provided . + /// Replaces the moods of the track with the provided . /// - /// The credits of the media contributors of the track. - public void UpdateCredits(IReadOnlyCollection credits) + /// The moods of the track. + internal void UpdateMoods(IReadOnlyCollection moods) { // replace the contents of the collection in place, preserving the readonly reference invariants of the entity - _credits.Clear(); - _credits.AddRange(credits); + _moods.Clear(); + _moods.AddRange(moods); + } + + /// + /// Replaces the ISRCs of the track with the provided . + /// + /// The ISRCs of the track. + internal void UpdateIsrcs(IReadOnlyCollection isrcs) + { + // replace the contents of the collection in place, preserving the readonly reference invariants of the entity + _isrcs.Clear(); + _isrcs.AddRange(isrcs); + } + + /// + /// Replaces the media contributors of the track with the provided . + /// + /// The media contributors of the track. + internal void UpdateContributors(IReadOnlyCollection contributors) + { + // replace the contents of the collection in place, preserving the readonly reference invariants of the entity + _contributors.Clear(); + _contributors.AddRange(contributors); + } + + /// + /// Replaces the ratings of the track with the provided . + /// + /// The ratings of the track. + internal void UpdateRatings(IReadOnlyCollection ratings) + { + // replace the contents of the collection in place, preserving the readonly reference invariants of the entity + _ratings.Clear(); + _ratings.AddRange(ratings); + } + + /// + /// Updates the details of the track, without touching the moods, the ISRCs, the media contributors, and the ratings. + /// + /// The file system path of the track. + /// The audio metadata of the track. + /// The number of the track on its disc. + /// The optional number of the disc the track belongs to. + /// 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. + /// 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, + AudioMetadata metadata, + int trackNumber, + Optional discNumber, + Optional script, + Optional key, + Optional bpm, + Optional work, + Optional musicBrainzRecordingId, + Optional musicBrainzTrackId, + Optional musicBrainzWorkId) + { + Path = path; + Metadata = metadata; + TrackNumber = trackNumber; + DiscNumber = discNumber; + Script = script; + Key = key; + Bpm = bpm; + 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/ValueObjects/Barcode.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Barcode.cs index 82282edd..83bdc2eb 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Barcode.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Barcode.cs @@ -38,7 +38,7 @@ public sealed class Barcode : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static Result Create(string? value) + public static Result Create(string value) { if (string.IsNullOrWhiteSpace(value)) return Errors.Music.BarcodeValueCannotBeEmpty; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Isrc.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Isrc.cs index 7fe8c356..2c87c0be 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Isrc.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/Isrc.cs @@ -38,7 +38,7 @@ public sealed class Isrc : ValueObject /// /// An containing either a successfully created , or an error message. /// - public static Result Create(string? value) + public static Result Create(string value) { if (string.IsNullOrWhiteSpace(value)) return Errors.Music.IsrcValueCannotBeEmpty; diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MediaContributorCredit.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MediaContributorCredit.cs deleted file mode 100644 index 99f63868..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MediaContributorCredit.cs +++ /dev/null @@ -1,76 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; - -/// -/// Value Object for the credit of a media contributor in a music media element, carrying the role the contributor played. -/// The role carries both a free-form display name, as returned by the metadata providers, and the canonical category -/// the display name normalizes to, so that roles describing the same kind of contribution are never treated as distinct. -/// -[DebuggerDisplay("{RoleDisplayName}")] -public sealed class MediaContributorCredit : ValueObject -{ - /// - /// Gets the unique identifier of the credited media contributor. - /// - public MediaContributorId ContributorId { get; } - - /// - /// Gets the display name of the role the contributor played. - /// - public string RoleDisplayName { get; } - - /// - /// Gets the canonical category of the role the contributor played. - /// - public MediaContributorRoleCategory RoleCategory { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The unique identifier of the credited media contributor. - /// The display name of the role the contributor played. - /// The canonical category of the role the contributor played. - private MediaContributorCredit(MediaContributorId contributorId, string roleDisplayName, MediaContributorRoleCategory roleCategory) - { - ContributorId = contributorId; - RoleDisplayName = roleDisplayName; - RoleCategory = roleCategory; - } - - /// - /// Creates a new instance of the class. - /// - /// The unique identifier of the credited media contributor. - /// The display name of the role the contributor played. - /// The canonical category of the role the contributor played. - /// - /// An containing either a successfully created , or an error message. - /// - public static Result Create(MediaContributorId contributorId, string roleDisplayName, MediaContributorRoleCategory roleCategory) - { - if (string.IsNullOrWhiteSpace(roleDisplayName)) - return Errors.Music.CreditRoleDisplayNameCannotBeEmpty; - - return new MediaContributorCredit(contributorId, roleDisplayName, roleCategory); - } - - /// - /// Gets the list of items that define equality of the object. - /// - /// A list of items defining the equality. - public override IEnumerable GetEqualityComponents() - { - yield return ContributorId; - yield return RoleDisplayName; - yield return RoleCategory; - } -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzId.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzId.cs index 37501bd7..fc5ea56e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzId.cs @@ -1,7 +1,5 @@ #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; @@ -34,28 +32,11 @@ public sealed class MusicBrainzId : ValueObject /// /// The value used to create the instance. /// The created instance. - public static Result Create(Guid value) + public static MusicBrainzId Create(Guid value) { return new MusicBrainzId(value); } - /// - /// Creates a new instance of the class, from a . - /// - /// The value used to create the instance. - /// - /// An containing either a successfully created , or an error message. - /// - public static Result Create(string? value) - { - if (string.IsNullOrWhiteSpace(value)) - return Errors.Music.MusicBrainzIdInvalidFormat; - if (!Guid.TryParse(value, out Guid parsedValue)) - return Errors.Music.MusicBrainzIdInvalidFormat; - - return new MusicBrainzId(parsedValue); - } - /// /// Gets the list of items that define equality of the object. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributor.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributor.cs new file mode 100644 index 00000000..3f2690c8 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributor.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Value Object for a media contributor of a music media element, carrying the role the contributor played. +/// The media contributor is identified only by its Id, duplicated from the Media Contributor bounded context, and the role is +/// the canonical role the contributor played, used as the key of its localized display string. +/// +[DebuggerDisplay("{Role}")] +public sealed class MusicMediaContributor : ValueObject +{ + /// + /// Gets the unique identifier of the media contributor. + /// + public MediaContributorId ContributorId { get; } + + /// + /// Gets the role the contributor played. + /// + public MediaContributorRole Role { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the media contributor. + /// The role the contributor played. + private MusicMediaContributor(MediaContributorId contributorId, MediaContributorRole role) + { + ContributorId = contributorId; + Role = role; + } + + /// + /// Creates a new instance of the class. + /// + /// The unique identifier of the media contributor. + /// The role the contributor played. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(MediaContributorId contributorId, MediaContributorRole role) + { + return new MusicMediaContributor(contributorId, role); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return ContributorId; + yield return Role; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs index bad71749..89190f99 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderService.cs @@ -37,15 +37,15 @@ internal class DirectoryProviderService : IDirectoryProviderService /// Retrieves a list of subdirectory paths from the specified path. /// /// The path from which to retrieve the subdirectory paths. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of directory paths or an error. - public Result> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements) + public Result> GetSubdirectoryPaths(FileSystemPathId path, bool shouldIncludeHiddenElements) { - // 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.ListDirectory, false)) return Errors.Permission.UnauthorizedAccess; return Result.From(_fileSystem.Directory.GetDirectories(path.Path) - .Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden) + .Where(path => shouldIncludeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden) .OrderBy(path => path) .Select(path => path.EndsWith(_fileSystem.Path.DirectorySeparatorChar) ? path : path + _fileSystem.Path.DirectorySeparatorChar) .Select(path => FileSystemPathId.Create(path)) @@ -63,7 +63,7 @@ internal class DirectoryProviderService : IDirectoryProviderService { try { - // File.GetAttributes is used for both directories and files + // File.GetAttributes is used for both directories and files. return _fileSystem.File.GetAttributes(path); } catch @@ -101,7 +101,7 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing either the optional last write time of if available, or an error. public Result> GetLastWriteTime(FileSystemPathId path) { - // 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.ReadProperties, false)) return Errors.Permission.UnauthorizedAccess; return Optional.FromNullable(_fileSystem.Directory.GetLastWriteTime(path.Path)); @@ -114,7 +114,7 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing the optional creation time of if available, or an error. public Result> GetCreationTime(FileSystemPathId path) { - // 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.ReadProperties, false)) return Errors.Permission.UnauthorizedAccess; return Optional.FromNullable(_fileSystem.Directory.GetCreationTime(path.Path)); @@ -128,10 +128,10 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing either the path of a created directory, or an error. public Result CreateDirectory(FileSystemPathId path, string name) { - // to create a directory, its parent directory must be writable + // To create a directory, its parent directory must be writable. if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Write, false)) return Errors.Permission.UnauthorizedAccess; - // create the directory and return its absolute path + // Create the directory and return its absolute path. string directoryPath = _fileSystem.Directory.CreateDirectory(_fileSystem.Path.Combine(path.Path, name)).FullName; return FileSystemPathId.Create(directoryPath); } @@ -141,28 +141,28 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the copied directory, or an error. - public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting) { - // check if the source directory exists + // Check if the source directory exists. if (!_fileSystem.Directory.Exists(sourcePath.Path)) return Errors.FileSystemManagement.DirectoryNotFound; string destPath = CreateUniqueDirectoryPath(destinationPath.Path); try { - // create the new directory + // Create the new directory. IDirectoryInfo destDirInfo = _fileSystem.DirectoryInfo.New(_fileSystem.Directory.CreateDirectory(destPath).FullName); - // get the information of the source directory + // Get the information of the source directory. IDirectoryInfo sourceDirInfo = _fileSystem.DirectoryInfo.New(sourcePath.Path); - // copy all files + // Copy all files. foreach (IFileInfo fileInfo in sourceDirInfo.GetFiles()) { string targetFilePath = _fileSystem.Path.Combine(destPath, fileInfo.Name); - fileInfo.CopyTo(targetFilePath, overrideExisting); - _fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // preserve file attributes + fileInfo.CopyTo(targetFilePath, shouldOverrideExisting); + _fileSystem.File.SetAttributes(targetFilePath, fileInfo.Attributes); // Preserve file attributes. } - // copy all subdirectories + // Copy all subdirectories. foreach (IDirectoryInfo subDirInfo in sourceDirInfo.GetDirectories()) { Result newSourcePathResult = FileSystemPathId.Create(subDirInfo.FullName); @@ -171,8 +171,8 @@ internal class DirectoryProviderService : IDirectoryProviderService Result newDestinationPathResult = FileSystemPathId.Create(_fileSystem.Path.Combine(destPath, subDirInfo.Name)); if (newDestinationPathResult.IsFailure) return newDestinationPathResult.Errors; - // recursive call - Result copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, overrideExisting); + // Recursive call. + Result copySubDirResult = CopyDirectory(newSourcePathResult.Value, newDestinationPathResult.Value, shouldOverrideExisting); if (copySubDirResult.IsFailure) return copySubDirResult.Errors; } @@ -193,7 +193,7 @@ internal class DirectoryProviderService : IDirectoryProviderService { string destPath = destinationPath; int copyNumber = 1; - // check if the destination directory exists and create a unique directory name + // Check if the destination directory exists and create a unique directory name. while (_fileSystem.Directory.Exists(destPath) || _fileSystem.File.Exists(destPath)) destPath = $"{destinationPath} - Copy ({copyNumber++})"; return destPath; @@ -204,20 +204,20 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting) { - // check if the source directory exists + // Check if the source directory exists. if (!_fileSystem.Directory.Exists(sourcePath.Path)) return Errors.FileSystemManagement.DirectoryNotFound; try { - // if the destination directory does not exist, perform a simple move + // If the destination directory does not exist, perform a simple move. if (!_fileSystem.Directory.Exists(destinationPath.Path)) _fileSystem.Directory.Move(sourcePath.Path, destinationPath.Path); else - MergeDirectories(sourcePath.Path, destinationPath.Path, overrideExisting); // if the destination directory exists, perform a merge based on the overwrite policy + MergeDirectories(sourcePath.Path, destinationPath.Path, shouldOverrideExisting); // If the destination directory exists, perform a merge based on the overwrite policy. return FileSystemPathId.Create(destinationPath.Path); } catch @@ -231,39 +231,39 @@ internal class DirectoryProviderService : IDirectoryProviderService /// /// The source directory to be merged. /// The destination directory to be merged. - /// Whether to override existing files. - private void MergeDirectories(string sourceDir, string destDir, bool overwrite) + /// Whether to override existing files. + private void MergeDirectories(string sourceDir, string destDir, bool shouldOverwrite) { - // merge files from source directory to destination directory + // Merge files from source directory to destination directory. foreach (string sourceFilePath in _fileSystem.Directory.GetFiles(sourceDir)) { string fileName = _fileSystem.Path.GetFileName(sourceFilePath); string destFilePath = _fileSystem.Path.Combine(destDir, fileName); - // if a file with the same name exists in the destination + // If a file with the same name exists in the destination. if (_fileSystem.File.Exists(destFilePath)) { - if (overwrite) + if (shouldOverwrite) { - // overwrite the file in the destination directory + // Overwrite the file in the destination directory. _fileSystem.File.Delete(destFilePath); _fileSystem.File.Move(sourceFilePath, destFilePath); } } else - _fileSystem.File.Move(sourceFilePath, destFilePath); // move the file if it does not exist in the destination directory + _fileSystem.File.Move(sourceFilePath, destFilePath); // Move the file if it does not exist in the destination directory. } - // recursively merge subdirectories + // Recursively merge subdirectories. foreach (string sourceSubDirPath in _fileSystem.Directory.GetDirectories(sourceDir)) { string subDirName = _fileSystem.Path.GetFileName(sourceSubDirPath); string destSubDirPath = _fileSystem.Path.Combine(destDir, subDirName); - // if the subdirectory does not exist in the destination, move it + // If the subdirectory does not exist in the destination, move it. if (!_fileSystem.Directory.Exists(destSubDirPath)) _fileSystem.Directory.Move(sourceSubDirPath, destSubDirPath); else - MergeDirectories(sourceSubDirPath, destSubDirPath, overwrite); // if the subdirectory exists, recursively merge its contents + MergeDirectories(sourceSubDirPath, destSubDirPath, shouldOverwrite); // If the subdirectory exists, recursively merge its contents. } - // after merging the contents, delete the source directory if it's now empty + // After merging the contents, delete the source directory if it's now empty. if (!_fileSystem.Directory.EnumerateFileSystemEntries(sourceDir).Any()) _fileSystem.Directory.Delete(sourceDir); } @@ -276,22 +276,22 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing either the absolute path of the renamed directory, or an error. public Result RenameDirectory(FileSystemPathId path, string name) { - // to rename a directory, its parent directory must be writable - string? parentDirectory = _fileSystem.Directory.GetParent(path.Path)?.FullName; - if (!string.IsNullOrEmpty(parentDirectory)) + // To rename a directory, its parent directory must be writable. + Optional parentDirectory = Optional.FromNullable(_fileSystem.Directory.GetParent(path.Path)?.FullName); + if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value)) { - Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value); if (parendDirectoryResult.IsFailure) return parendDirectoryResult.Errors; - string? newDirectory = _fileSystem.Path.Combine(parentDirectory, name); - if (!string.IsNullOrEmpty(newDirectory)) + Optional newDirectory = Optional.FromNullable(_fileSystem.Path.Combine(parentDirectory.Value, name)); + if (newDirectory.HasValue && !string.IsNullOrEmpty(newDirectory.Value)) { - Result newDirectoryPathResult = FileSystemPathId.Create(newDirectory); + Result newDirectoryPathResult = FileSystemPathId.Create(newDirectory.Value); if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write, false)) return Errors.Permission.UnauthorizedAccess; - // to rename a directory, it must be executable + // To rename a directory, it must be executable. if (!_fileSystemPermissionsService.CanAccessPath(path, FileAccessMode.Execute, false)) return Errors.Permission.UnauthorizedAccess; _fileSystem.Directory.Move(path.Path, newDirectoryPathResult.Value.Path); @@ -311,7 +311,7 @@ internal class DirectoryProviderService : IDirectoryProviderService /// An containing either the result of deleting a directory, or an error. public Result DeleteDirectory(FileSystemPathId path) { - // 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.Delete, false)) return Errors.Permission.UnauthorizedAccess; _fileSystem.DirectoryInfo.New(path.Path).Delete(true); diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs index f404edc1..54c925c4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryService.cs @@ -36,48 +36,48 @@ public class DirectoryService : IDirectoryService /// Retrieves subdirectories for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public Result> GetSubdirectories(string path, bool includeHiddenElements) + public Result> GetSubdirectories(string path, bool shouldIncludeHiddenElements) { Result fileSystemPathIdResult = FileSystemPathId.Create(path); if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - return GetSubdirectories(fileSystemPathIdResult.Value, includeHiddenElements); + return GetSubdirectories(fileSystemPathIdResult.Value, shouldIncludeHiddenElements); } /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public Result> GetSubdirectories(Directory directory, bool includeHiddenElements) + public Result> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements) { - return GetSubdirectories(directory.Id, includeHiddenElements); + return GetSubdirectories(directory.Id, shouldIncludeHiddenElements); } /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - public Result> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements) + public Result> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements) { - // retrieve the list of subdirectories - Result> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, includeHiddenElements); + // Retrieve the list of subdirectories. + Result> subdirectoryPathsResult = _environmentContext.DirectoryProviderService.GetSubdirectoryPaths(path, shouldIncludeHiddenElements); if (subdirectoryPathsResult.IsFailure) return subdirectoryPathsResult.Errors; List result = []; foreach (FileSystemPathId subPath in subdirectoryPathsResult.Value) { - // extract directory details + // Extract directory details. Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(subPath); Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(subPath); Result> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(subPath); - // if any error occurred, mark directory as Inaccessible + // If any error occurred, mark the directory as inaccessible. if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { Result errorDirResult = Directory.Create(subPath, !dirNameResult.IsFailure ? dirNameResult.Value : null!, @@ -123,7 +123,7 @@ public class DirectoryService : IDirectoryService /// An containing either the result of creating a directory, or an error. public Result CreateDirectory(FileSystemPathId path, string name) { - // first, check if the directory about to be created does not already exist + // First, check that the target directory does not already exist. Result combinedPath = _platformContext.PathStrategy.CombinePath(path, name); if (combinedPath.IsFailure) return combinedPath.Errors; @@ -134,14 +134,14 @@ public class DirectoryService : IDirectoryService return Errors.FileSystemManagement.DirectoryAlreadyExists; else { - // create the new directory + // Create the new directory. Result newDirectoryPathResult = _environmentContext.DirectoryProviderService.CreateDirectory(path, name); if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); Result> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); - // if any error occurred, mark directory as Inaccessible + // If any error occurred, mark the directory as inaccessible. if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { Result errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!, @@ -164,11 +164,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the path where the directory to be copied is located. /// String representation of the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a copied directory, or an error. - public Result CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + public Result CopyDirectory(string sourcePath, string destinationPath, Optional shouldOverrideExisting) { - // make sure the paths are in the expected format + // Make sure the paths are in the expected format. if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator)) sourcePath += _platformContext.PathStrategy.PathSeparator; if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) @@ -179,7 +179,7 @@ public class DirectoryService : IDirectoryService Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; - return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + return CopyDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value); } /// @@ -187,9 +187,9 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the copied directory, or an error. - public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting) { Result directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); if (directoryExists.IsFailure) @@ -198,8 +198,8 @@ public class DirectoryService : IDirectoryService return Errors.FileSystemManagement.DirectoryNotFound; else { - // copy the directory - Result newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, overrideExisting); + // Copy the directory. + Result newDirectory = _environmentContext.DirectoryProviderService.CopyDirectory(sourcePath, destinationPath, shouldOverrideExisting); throw new NotImplementedException(); } @@ -210,11 +210,11 @@ public class DirectoryService : IDirectoryService /// /// String representation of the path where the directory to be moved is located. /// String representation of the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - public Result MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting) + public Result MoveDirectory(string sourcePath, string destinationPath, Optional shouldOverrideExisting) { - // make sure the paths are in the expected format + // Make sure the paths are in the expected format. if (!sourcePath.EndsWith(_platformContext.PathStrategy.PathSeparator)) sourcePath += _platformContext.PathStrategy.PathSeparator; if (!destinationPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) @@ -225,7 +225,7 @@ public class DirectoryService : IDirectoryService Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationPath); if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; - return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + return MoveDirectory(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value); } /// @@ -233,9 +233,9 @@ public class DirectoryService : IDirectoryService /// /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the moved directory, or an error. - public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting) + public Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting) { Result directoryExists = _environmentContext.DirectoryProviderService.DirectoryExists(sourcePath); if (directoryExists.IsFailure) @@ -244,8 +244,8 @@ public class DirectoryService : IDirectoryService return Errors.FileSystemManagement.DirectoryNotFound; else { - // move the directory - Result newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, overrideExisting); + // Move the directory. + Result newDirectory = _environmentContext.DirectoryProviderService.MoveDirectory(sourcePath, destinationPath, shouldOverrideExisting); throw new NotImplementedException(); } @@ -273,7 +273,7 @@ public class DirectoryService : IDirectoryService /// An containing either the renamed directory, or an error. public Result RenameDirectory(FileSystemPathId path, string name) { - // first, check if the directory about to be created does not already exist + // First, check that the target directory does not already exist. Result combinedPath = _platformContext.PathStrategy.CombinePath(path, name); if (combinedPath.IsFailure) return combinedPath.Errors; @@ -284,14 +284,14 @@ public class DirectoryService : IDirectoryService return Errors.FileSystemManagement.DirectoryAlreadyExists; else { - // rename the directory + // Rename the directory. Result newDirectoryPathResult = _environmentContext.DirectoryProviderService.RenameDirectory(path, name); if (newDirectoryPathResult.IsFailure) return newDirectoryPathResult.Errors; Result dirNameResult = _environmentContext.DirectoryProviderService.GetFileName(newDirectoryPathResult.Value); Result> dateModifiedResult = _environmentContext.DirectoryProviderService.GetLastWriteTime(newDirectoryPathResult.Value); Result> dateCreatedResult = _environmentContext.DirectoryProviderService.GetCreationTime(newDirectoryPathResult.Value); - // if any error occurred, mark directory as Inaccessible + // If any error occurred, mark the directory as inaccessible. if (dirNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure) { Result errorDirResult = Directory.Create(newDirectoryPathResult.Value, !dirNameResult.IsFailure ? dirNameResult.Value : null!, diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs index 452e3667..e52a47ca 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderService.cs @@ -36,15 +36,15 @@ internal class FileProviderService : IFileProviderService /// Retrieves a list of file paths at the specified path. /// /// The path for which to retrieve the list of files. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of file paths or an error. - public Result> GetFilePaths(FileSystemPathId path, bool includeHiddenElements) + public Result> GetFilePaths(FileSystemPathId path, bool shouldIncludeHiddenElements) { - // 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.ListDirectory)) return Errors.Permission.UnauthorizedAccess; return Result.From(_fileSystem.Directory.GetFiles(path.Path) - .Where(path => includeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden) + .Where(path => shouldIncludeHiddenElements || (GetAttributes(path) & FileAttributes.Hidden) != FileAttributes.Hidden) .OrderBy(path => path) .Select(path => FileSystemPathId.Create(path)) .Where(pathIdResult => !pathIdResult.IsFailure) @@ -61,7 +61,7 @@ internal class FileProviderService : IFileProviderService { try { - // File.GetAttributes is used for both directories and files + // File.GetAttributes is used for both directories and files. return _fileSystem.File.GetAttributes(path); } catch @@ -97,7 +97,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the contents of a file at the specified path, or an error. public Result GetFileAsync(FileSystemPathId path) { - // 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; return _fileSystem.File.ReadAllBytes(path.Path); @@ -110,7 +110,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the optional last write time of if available, or an error. public Result> GetLastWriteTime(FileSystemPathId path) { - // 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.ReadProperties)) return Errors.Permission.UnauthorizedAccess; return Optional.FromNullable(_fileSystem.File.GetLastWriteTime(path.Path)); @@ -123,7 +123,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the optional creation time of if available, or an error. public Result> GetCreationTime(FileSystemPathId path) { - // 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.ReadProperties)) return Errors.Permission.UnauthorizedAccess; return Optional.FromNullable(_fileSystem.File.GetCreationTime(path.Path)); @@ -136,7 +136,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the size of or an error. public Result GetSize(FileSystemPathId path) { - // 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.ReadProperties)) return Errors.Permission.UnauthorizedAccess; return _fileSystem.FileInfo.New(path.Path)?.Length ?? 0; @@ -147,27 +147,27 @@ internal class FileProviderService : IFileProviderService /// /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the copied file, or an error. - public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting) { - // check if the source file exists + // Check if the source file exists. if (!_fileSystem.File.Exists(sourceFilePath.Path)) return Errors.FileSystemManagement.FileNotFound; string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName); - // when copying a file to the same location, just copy it with a new name + // When copying a file to the same location, just copy it with a new name. if (_fileSystem.Path.GetDirectoryName(sourceFilePath.Path) == destinationDirectoryPath.Path) destinationFilePath = CreateUniqueFilePath(destinationFilePath); else - // check if there is already a file with the same name as the copied file, in the destination directory + // Check if there is already a file with the same name as the copied file, in the destination directory. if (_fileSystem.File.Exists(destinationFilePath)) - if (!overrideExisting) + if (!shouldOverrideExisting) return Errors.FileSystemManagement.FileAlreadyExists; try { - _fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, overrideExisting); // copy the file - _fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // preserve file attributes + _fileSystem.File.Copy(sourceFilePath.Path, destinationFilePath, shouldOverrideExisting); // Copy the file. + _fileSystem.File.SetAttributes(destinationFilePath, _fileSystem.File.GetAttributes(sourceFilePath.Path)); // Preserve file attributes. return FileSystemPathId.Create(destinationFilePath); } catch @@ -177,21 +177,23 @@ internal class FileProviderService : IFileProviderService } /// - /// Creates a file path that is unique + /// Creates a file path that is unique. /// /// The path from which to generate the unique file path. /// A unique directory path. private string CreateUniqueFilePath(string destinationFilePath) { - string? directory = _fileSystem.Path.GetDirectoryName(destinationFilePath); - string? filename = _fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath); - string? extension = _fileSystem.Path.GetExtension(destinationFilePath); + Optional directory = Optional.FromNullable(_fileSystem.Path.GetDirectoryName(destinationFilePath)); + Optional filename = Optional.FromNullable(_fileSystem.Path.GetFileNameWithoutExtension(destinationFilePath)); + Optional extension = Optional.FromNullable(_fileSystem.Path.GetExtension(destinationFilePath)); string destFilePath = destinationFilePath; int copyNumber = 1; - // check if the destination file exists and create a unique file name - if (!string.IsNullOrEmpty(directory) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(extension)) + // Check if the destination file exists and create a unique file name. + if (directory.HasValue && !string.IsNullOrEmpty(directory.Value) + && filename.HasValue && !string.IsNullOrEmpty(filename.Value) + && extension.HasValue && !string.IsNullOrEmpty(extension.Value)) while (_fileSystem.File.Exists(destFilePath)) - destFilePath = _fileSystem.Path.Combine(directory, $"{filename} - Copy ({copyNumber++}){extension}"); + destFilePath = _fileSystem.Path.Combine(directory.Value, $"{filename.Value} - Copy ({copyNumber++}){extension.Value}"); return destFilePath; } @@ -200,23 +202,23 @@ internal class FileProviderService : IFileProviderService /// /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting) { - // check if the source file exists + // Check if the source file exists. if (!_fileSystem.File.Exists(sourceFilePath.Path)) return Errors.FileSystemManagement.FileNotFound; try { string fileName = _fileSystem.Path.GetFileName(sourceFilePath.Path); string destinationFilePath = _fileSystem.Path.Combine(destinationDirectoryPath.Path, fileName); - // if the destination file does not exist, perform a simple move + // If the destination file does not exist, perform a simple move. if (!_fileSystem.File.Exists(destinationFilePath)) _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath); else - if (overrideExisting) - _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, overrideExisting); + if (shouldOverrideExisting) + _fileSystem.File.Move(sourceFilePath.Path, destinationFilePath, shouldOverrideExisting); else return Errors.FileSystemManagement.FileAlreadyExists; return FileSystemPathId.Create(destinationFilePath); @@ -235,19 +237,19 @@ internal class FileProviderService : IFileProviderService /// An containing either the absolute path of the renamed file, or an error. public Result RenameFile(FileSystemPathId path, string name) { - string? parentDirectory = _fileSystem.FileInfo.New(path.Path)?.DirectoryName; - if (!string.IsNullOrEmpty(parentDirectory)) + Optional parentDirectory = Optional.FromNullable(_fileSystem.FileInfo.New(path.Path)?.DirectoryName); + if (parentDirectory.HasValue && !string.IsNullOrEmpty(parentDirectory.Value)) { - Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory); + Result parendDirectoryResult = FileSystemPathId.Create(parentDirectory.Value); if (parendDirectoryResult.IsFailure) return parendDirectoryResult.Errors; - string? newFile = _fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name); - if (!string.IsNullOrEmpty(newFile)) + Optional newFile = Optional.FromNullable(_fileSystem.Path.Combine(parendDirectoryResult.Value.Path, name)); + if (newFile.HasValue && !string.IsNullOrEmpty(newFile.Value)) { - Result newFilePathResult = FileSystemPathId.Create(newFile); + Result newFilePathResult = FileSystemPathId.Create(newFile.Value); if (newFilePathResult.IsFailure) return newFilePathResult.Errors; - // renaming a file only requires write access to its parent directory, never execute access to the file itself + // Renaming a file only requires write access to its parent directory, never execute access to the file itself. if (!_fileSystemPermissionsService.CanAccessPath(parendDirectoryResult.Value, FileAccessMode.Write)) return Errors.Permission.UnauthorizedAccess; _fileSystem.File.Move(path.Path, newFilePathResult.Value.Path); @@ -267,7 +269,7 @@ internal class FileProviderService : IFileProviderService /// An containing either the result of deleting a file, or an error. public Result DeleteFile(FileSystemPathId path) { - // 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.Delete)) return Errors.Permission.UnauthorizedAccess; _fileSystem.File.Delete(path.Path); diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs index dc5de274..b4404c1c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileService.cs @@ -35,50 +35,50 @@ public class FileService : IFileService /// Retrieves files for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public Result> GetFiles(string path, bool includeHiddenElements) + public Result> GetFiles(string path, bool shouldIncludeHiddenElements) { Result fileSystemPathIdResult = FileSystemPathId.Create(path); if (fileSystemPathIdResult.IsFailure) return fileSystemPathIdResult.Errors; - return GetFiles(fileSystemPathIdResult.Value, includeHiddenElements); + return GetFiles(fileSystemPathIdResult.Value, shouldIncludeHiddenElements); } /// /// Retrieves files associated with a given file. /// /// The file object. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public Result> GetFiles(File file, bool includeHiddenElements) + public Result> GetFiles(File file, bool shouldIncludeHiddenElements) { - return GetFiles(file.Id, includeHiddenElements); + return GetFiles(file.Id, shouldIncludeHiddenElements); } /// /// Retrieves files for a specified file path Id. /// /// Identifier for the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - public Result> GetFiles(FileSystemPathId path, bool includeHiddenElements) + public Result> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements) { - // retrieve the list of files - Result> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, includeHiddenElements); + // Retrieve the list of files. + Result> filePathsResult = _environmentContext.FileProviderService.GetFilePaths(path, shouldIncludeHiddenElements); if (filePathsResult.IsFailure) return filePathsResult.Errors; List result = []; IEnumerable filePaths = filePathsResult.Value; foreach (FileSystemPathId filePath in filePaths) { - // extract file details and add to the result list + // Extract file details and add them to the result list. Result fileNameResult = _environmentContext.FileProviderService.GetFileName(filePath); Result> dateModifiedResult = _environmentContext.FileProviderService.GetLastWriteTime(filePath); Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(filePath); Result sizeResult = _environmentContext.FileProviderService.GetSize(filePath); long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0; - // if any of the details returned an error, set inaccessible status + // If any of the details returned an error, set the inaccessible status. if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure) { Result errorFileResult = File.Create(filePath, !fileNameResult.IsFailure ? fileNameResult.Value : null!, @@ -107,13 +107,13 @@ public class FileService : IFileService /// /// String representation of the path where the file to be copied is located. /// String representation of the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a copied file, or an error. - public Result CopyFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + public Result CopyFile(string sourceFilePath, string destinationDirectoryPath, Optional shouldOverrideExisting) { if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) return Errors.FileSystemManagement.InvalidPath; - // make sure the paths are in the expected format + // Make sure the paths are in the expected format. if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; Result fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); @@ -122,7 +122,7 @@ public class FileService : IFileService Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; - return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + return CopyFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value); } /// @@ -130,9 +130,9 @@ public class FileService : IFileService /// /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the copied file, or an error. - public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting) { Result fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); if (fileExists.IsFailure) @@ -141,8 +141,8 @@ public class FileService : IFileService return Errors.FileSystemManagement.FileNotFound; else { - // copy the file - Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + // Copy the file. + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting); if (copyFileResult.IsFailure) return copyFileResult.Errors; Result fileNameResult = _environmentContext.FileProviderService.GetFileName(copyFileResult.Value); @@ -150,7 +150,7 @@ public class FileService : IFileService Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(copyFileResult.Value); Result sizeResult = _environmentContext.FileProviderService.GetSize(copyFileResult.Value); long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0; - // if any of the details returned an error, set inaccessible status + // If any of the details returned an error, set the inaccessible status. if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure) { Result errorFileResult = File.Create(copyFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, @@ -173,13 +173,13 @@ public class FileService : IFileService /// /// String representation of the path where the file to be moved is located. /// String representation of the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - public Result MoveFile(string sourceFilePath, string destinationDirectoryPath, bool? overrideExisting) + public Result MoveFile(string sourceFilePath, string destinationDirectoryPath, Optional shouldOverrideExisting) { if (string.IsNullOrWhiteSpace(destinationDirectoryPath)) return Errors.FileSystemManagement.InvalidPath; - // make sure the paths are in the expected format + // Make sure the paths are in the expected format. if (!destinationDirectoryPath.EndsWith(_platformContext.PathStrategy.PathSeparator)) destinationDirectoryPath += _platformContext.PathStrategy.PathSeparator; Result fileSystemSourcePathIdResult = FileSystemPathId.Create(sourceFilePath); @@ -188,7 +188,7 @@ public class FileService : IFileService Result fileSystemDestinationPathIdResult = FileSystemPathId.Create(destinationDirectoryPath); if (fileSystemDestinationPathIdResult.IsFailure) return fileSystemDestinationPathIdResult.Errors; - return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, overrideExisting ?? false); + return MoveFile(fileSystemSourcePathIdResult.Value, fileSystemDestinationPathIdResult.Value, shouldOverrideExisting.Value); } /// @@ -196,9 +196,9 @@ public class FileService : IFileService /// /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the moved file, or an error. - public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting) + public Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting) { Result fileExists = _environmentContext.FileProviderService.FileExists(sourceFilePath); if (fileExists.IsFailure) @@ -207,8 +207,8 @@ public class FileService : IFileService return Errors.FileSystemManagement.FileNotFound; else { - // move the file - Result moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, overrideExisting); + // Move the file. + Result moveFileResult = _environmentContext.FileProviderService.MoveFile(sourceFilePath, destinationDirectoryPath, shouldOverrideExisting); if (moveFileResult.IsFailure) return moveFileResult.Errors; Result fileNameResult = _environmentContext.FileProviderService.GetFileName(moveFileResult.Value); @@ -216,7 +216,7 @@ public class FileService : IFileService Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(moveFileResult.Value); Result sizeResult = _environmentContext.FileProviderService.GetSize(moveFileResult.Value); long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0; - // if any of the details returned an error, set inaccessible status + // If any of the details returned an error, set the inaccessible status. if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure) { Result errorFileResult = File.Create(moveFileResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, @@ -256,7 +256,7 @@ public class FileService : IFileService /// An containing either the renamed file, or an error. public Result RenameFile(FileSystemPathId path, string name) { - // first, check if the directory about to be created does not already exist + // First, check that the target file does not already exist. Result combinedPath = _platformContext.PathStrategy.CombinePath(path, name); if (combinedPath.IsFailure) return combinedPath.Errors; @@ -267,7 +267,7 @@ public class FileService : IFileService return Errors.FileSystemManagement.FileAlreadyExists; else { - // rename the file + // Rename the file. Result newFilePathResult = _environmentContext.FileProviderService.RenameFile(path, name); if (newFilePathResult.IsFailure) return newFilePathResult.Errors; @@ -276,7 +276,7 @@ public class FileService : IFileService Result> dateCreatedResult = _environmentContext.FileProviderService.GetCreationTime(newFilePathResult.Value); Result sizeResult = _environmentContext.FileProviderService.GetSize(newFilePathResult.Value); long size = !sizeResult.IsFailure ? sizeResult.Value ?? 0 : 0; - // if any of the details returned an error, set inaccessible status + // If any of the details returned an error, set the inaccessible status. if (fileNameResult.IsFailure || dateModifiedResult.IsFailure || dateCreatedResult.IsFailure || sizeResult.IsFailure) { Result errorFileResult = File.Create(newFilePathResult.Value, !fileNameResult.IsFailure ? fileNameResult.Value : null!, diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs index 668094c2..8120b5a2 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemPermissionsService.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; @@ -14,7 +15,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// /// Service for file system permissions. /// -internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: refactor towards abstractions that could allow testing +internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: Refactor towards abstractions that would allow testing. { private readonly IPlatformContextManager _platformContextManager; @@ -61,10 +62,10 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T switch (accessMode) { case FileAccessMode.ReadProperties: - // for properties, we only need to check if the path exists + // For properties, we only need to check if the path exists. return File.Exists(path) || Directory.Exists(path); case FileAccessMode.ReadContents: - // attempt to open the file for reading to verify read access + // Attempt to open the file for reading, to verify read access. if (File.Exists(path)) { FileStream fileStream = File.OpenRead(path); @@ -73,7 +74,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } return false; case FileAccessMode.Write: - // attempt to open the file for writing or verify directory exists + // Attempt to open the file for writing, or verify that the directory exists. if (File.Exists(path)) { FileStream fileStream = File.OpenWrite(path); @@ -82,11 +83,11 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } return Directory.Exists(path); case FileAccessMode.Execute: - // check Unix execute permission bit + // Check the Unix execute permission bit. FileInfo fileInfo = new(path); return (fileInfo.UnixFileMode & UnixFileMode.UserExecute) != 0; case FileAccessMode.ListDirectory: - // attempt to list directory contents to verify access + // Attempt to list the directory contents, to verify access. if (Directory.Exists(path)) { string[] _ = Directory.GetFiles(path); @@ -96,11 +97,11 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T case FileAccessMode.Delete: if (File.Exists(path)) { - // for files, check if parent directory is writable - string? directoryPath = Path.GetDirectoryName(path); - return directoryPath != null && HasWriteAccessToDirectory(directoryPath); + // For files, check if the parent directory is writable. + Optional directoryPath = Optional.FromNullable(Path.GetDirectoryName(path)); + return directoryPath.HasValue && HasWriteAccessToDirectory(directoryPath.Value); } - // for directories, check if the directory itself is writable + // For directories, check if the directory itself is writable. return Directory.Exists(path) && HasWriteAccessToDirectory(path); default: throw new ArgumentOutOfRangeException(nameof(accessMode), "Unknown FileAccessMode"); @@ -108,11 +109,11 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T } catch (UnauthorizedAccessException) { - return false; // access denied by the operating system + return false; // Access denied by the operating system. } catch (IOException) { - return false; // IO operation failed, indicating no access + return false; // IO operation failed, indicating no access. } } @@ -125,9 +126,9 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T { try { - // create a unique temporary filename + // Create a unique temporary filename. string temporaryFilePath = Path.Combine(path, string.Format(".test_{0}", Guid.NewGuid())); - // attempt to create and immediately delete a temporary file + // Attempt to create and immediately delete a temporary file. FileStream testStream = File.Create(temporaryFilePath); testStream.Dispose(); File.Delete(temporaryFilePath); @@ -154,7 +155,7 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T [SupportedOSPlatform("windows")] private static bool CanAccessPathWindows(string path, FileAccessMode accessMode, bool isFile = true) { - // translate to filesystem access modes (multiple can match per case) + // Translate to filesystem access modes (multiple can match per case). FileSystemRights rights = accessMode switch { FileAccessMode.ReadProperties => FileSystemRights.ReadAttributes, @@ -167,12 +168,12 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T }; if (rights == FileSystemRights.Delete) { - // when checking for delete permissions, we need to check the directory the file or directory resides in - string? parentDirectory = Directory.GetParent(path)?.FullName; - if (string.IsNullOrEmpty(parentDirectory)) - return false; // the path is either a root directory or has no parent, which we cannot delete - // checking for modify permission on the parent directory since delete requires modifying the parent contents - return HasAccess(FileSystemRights.Modify, parentDirectory, false); + // When checking for delete permissions, we need to check the directory the file or directory resides in. + Optional parentDirectory = Optional.FromNullable(Directory.GetParent(path)?.FullName); + if (!parentDirectory.HasValue || string.IsNullOrEmpty(parentDirectory.Value)) + return false; // The path is either a root directory or has no parent, which we cannot delete. + // Checking for the modify permission on the parent directory, since delete requires modifying the parent contents. + return HasAccess(FileSystemRights.Modify, parentDirectory.Value, false); } else if (HasAccess(rights, path, isFile)) @@ -181,9 +182,9 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T switch (accessMode) { case FileAccessMode.ReadProperties: - // just accessing file info for properties, without opening it + // Just access file info for properties, without opening it. FileSystemInfo fileSystemInfo = isFile ? new FileInfo(path) : new DirectoryInfo(path); - _ = fileSystemInfo.CreationTime; // trigger potential access denial + _ = fileSystemInfo.CreationTime; // Trigger a potential access denial. break; case FileAccessMode.ReadContents: using (FileStream stream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) @@ -209,14 +210,14 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T [SupportedOSPlatform("windows")] private static bool HasAccess(FileSystemRights rights, string path, bool isFile = true) { - bool allowAccess = false; + bool doesAllowAccess = false; AuthorizationRuleCollection acl; WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new(identity); - // get the collection of authorization rules that apply to the specified directory + // Get the collection of authorization rules that apply to the specified directory. try { - // some paths (ex: C:\Windows\System32\config) throw "unauthorized" exceptions even when trying to check if one is authorized to access them - how dumb is that??... + // Some paths, such as C:\Windows\System32\config, throw unauthorized exceptions even when only checking whether access is allowed. if (isFile) { FileInfo fileInfo = new(path); @@ -228,18 +229,18 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T acl = directoryInfo.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); } foreach (FileSystemAccessRule accessRule in acl) - // Check if the current rule applies to the current user or the groups they belong to + // Check if the current rule applies to the current user or the groups they belong to. if (identity?.User?.Equals(accessRule.IdentityReference) == true || principal.IsInRole((SecurityIdentifier)accessRule.IdentityReference)) if (accessRule.AccessControlType.Equals(AccessControlType.Deny) && (accessRule.FileSystemRights & rights) == rights) - return false; // if there's a deny rule that matches the specified rights, return false immediately + return false; // If there is a deny rule that matches the specified rights, deny access immediately. else if (accessRule.AccessControlType.Equals(AccessControlType.Allow) && (accessRule.FileSystemRights & rights) == rights) - allowAccess = true; + doesAllowAccess = true; } catch { return false; } - return allowAccess; + return doesAllowAccess; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs index 91d2ca69..38cee2d4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryProviderService.cs @@ -17,9 +17,9 @@ public interface IDirectoryProviderService /// Retrieves a list of subdirectory paths from the specified path. /// /// The path from which to retrieve the subdirectory paths. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of directory paths or an error. - Result> GetSubdirectoryPaths(FileSystemPathId path, bool includeHiddenElements); + Result> GetSubdirectoryPaths(FileSystemPathId path, bool shouldIncludeHiddenElements); /// /// Checks if a directory with the specified path exists. @@ -63,18 +63,18 @@ public interface IDirectoryProviderService /// /// Identifier for the path where the directory to be copied is located. /// Identifier for the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either the copied directory, or an error. - Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); + Result CopyDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting); /// /// Moves a directory located at to . /// /// Identifier for the path where the directory to be moved is located. /// Identifier for the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool overrideExisting); + Result MoveDirectory(FileSystemPathId sourcePath, FileSystemPathId destinationPath, bool shouldOverrideExisting); /// /// Renames a directory at the specified path. diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs index 96afe5aa..f5ee7823 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IDirectoryService.cs @@ -16,25 +16,25 @@ public interface IDirectoryService /// Retrieves subdirectories for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - Result> GetSubdirectories(string path, bool includeHiddenElements); + Result> GetSubdirectories(string path, bool shouldIncludeHiddenElements); /// /// Retrieves subdirectories for the given directory. /// /// Directory object to retrieve subdirectories for. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - Result> GetSubdirectories(Directory directory, bool includeHiddenElements); + Result> GetSubdirectories(Directory directory, bool shouldIncludeHiddenElements); /// /// Retrieves subdirectories for the specified file system path. /// /// Identifier for the file path. - /// Whether to include hidden subdirectories or not. + /// Whether to include hidden subdirectories or not. /// An containing either a collection of subdirectories or an error. - Result> GetSubdirectories(FileSystemPathId path, bool includeHiddenElements); + Result> GetSubdirectories(FileSystemPathId path, bool shouldIncludeHiddenElements); /// /// Creates a directory with the specified , at the specified . @@ -49,18 +49,18 @@ public interface IDirectoryService /// /// String representation of the path where the directory to be copied is located. /// String representation of the path where the directory will be copied. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a copied directory, or an error. - Result CopyDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + Result CopyDirectory(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Moves a directory located at to . /// /// String representation of the path where the directory to be moved is located. /// String representation of the path where the directory will be moved. - /// Whether to override existing directories, or not. + /// Whether to override existing directories, or not. /// An containing either a moved directory, or an error. - Result MoveDirectory(string sourcePath, string destinationPath, bool? overrideExisting); + Result MoveDirectory(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Renames a directory with the specified , at the specified . diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs index 591ebd67..a2b45416 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileProviderService.cs @@ -17,9 +17,9 @@ public interface IFileProviderService /// Retrieves a list of files at the specified path. /// /// The path for which to retrieve the list of files. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of file paths, or an error. - Result> GetFilePaths(FileSystemPathId path, bool includeHiddenElements); + Result> GetFilePaths(FileSystemPathId path, bool shouldIncludeHiddenElements); /// /// Retrieves the contents of a file at the specified path. @@ -68,18 +68,18 @@ public interface IFileProviderService /// /// Identifier for the path where the file to be copied is located. /// Identifier for the path of the directory where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either the copied file, or an error. - Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); + Result CopyFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting); /// /// Moves a file located at to . /// /// Identifier for the path where the file to be moved is located. /// Identifier for the path of the directory where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool overrideExisting); + Result MoveFile(FileSystemPathId sourceFilePath, FileSystemPathId destinationDirectoryPath, bool shouldOverrideExisting); /// /// Renames a file at the specified path. diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs index ece87ff5..4cb7b412 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IFileService.cs @@ -16,43 +16,43 @@ public interface IFileService /// Retrieves files for the specified string path. /// /// String representation of the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - Result> GetFiles(string path, bool includeHiddenElements); + Result> GetFiles(string path, bool shouldIncludeHiddenElements); /// /// Retrieves files associated with a given file. /// /// The file object. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - Result> GetFiles(File file, bool includeHiddenElements); + Result> GetFiles(File file, bool shouldIncludeHiddenElements); /// /// Retrieves files for a specified file path ID. /// /// Identifier for the file path. - /// Whether to include hidden files or not. + /// Whether to include hidden files or not. /// An containing either a collection of files or an error. - Result> GetFiles(FileSystemPathId path, bool includeHiddenElements); + Result> GetFiles(FileSystemPathId path, bool shouldIncludeHiddenElements); /// /// Copies a file located at to . /// /// String representation of the path where the file to be copied is located. /// String representation of the path where the file will be copied. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a copied file, or an error. - Result CopyFile(string sourcePath, string destinationPath, bool? overrideExisting); + Result CopyFile(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Moves a file located at to . /// /// String representation of the path where the file to be moved is located. /// String representation of the path where the file will be moved. - /// Whether to override existing files, or not. + /// Whether to override existing files, or not. /// An containing either a moved file, or an error. - Result MoveFile(string sourcePath, string destinationPath, bool? overrideExisting); + Result MoveFile(string sourcePath, string destinationPath, Optional shouldOverrideExisting); /// /// Renames a file with the specified , at the specified . diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index 34a03dab..598e44de 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -27,9 +27,9 @@ public interface IPathService /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - bool Exists(string path, bool includeHiddenElements = true); + bool Exists(string path, bool shouldIncludeHiddenElements = true); /// /// Tries to combine with . @@ -72,4 +72,12 @@ public interface IPathService /// The path for which to get the root. /// An containing the root of , or an error. Result GetPathRoot(string path); + + /// + /// Checks whether is located inside . + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + bool IsPathWithin(string path, string parentPath); } 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 02dadc41..18f0d79b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -50,21 +50,21 @@ public class PathService : IPathService /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - public bool Exists(string path, bool includeHiddenElements = true) + public bool Exists(string path, bool shouldIncludeHiddenElements = true) { Result newPathResult = FileSystemPathId.Create(path); if (newPathResult.IsFailure) return false; - return _platformContext.PathStrategy.Exists(newPathResult.Value, includeHiddenElements); + return _platformContext.PathStrategy.Exists(newPathResult.Value, shouldIncludeHiddenElements); } /// /// Tries to combine with . /// /// The path to be combined. - /// The name to be combined with the path. + /// The name to be combined with the path. /// An containing the combined path, or an error. public Result CombinePath(string path, string name) { @@ -127,28 +127,28 @@ public class PathService : IPathService char[] invalidChars = _platformContext.PathStrategy.GetInvalidPathSegmentCharsForPlatform(); char[] sanitizedChars = [.. name.Trim().Select(character => Array.IndexOf(invalidChars, character) >= 0 ? ' ' : character)]; - // collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing + // Collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing. List collapsedChars = []; - bool previousWasWhitespace = false; + bool wasPreviousWhitespace = false; foreach (char character in sanitizedChars) { if (char.IsWhiteSpace(character)) { - if (!previousWasWhitespace) + if (!wasPreviousWhitespace) collapsedChars.Add(' '); - previousWasWhitespace = true; + wasPreviousWhitespace = true; } else { collapsedChars.Add(character); - previousWasWhitespace = false; + wasPreviousWhitespace = false; } } string sanitized = new string([.. collapsedChars]).Trim(); if (string.Equals(sanitized, ".", StringComparison.Ordinal) || string.Equals(sanitized, "..", StringComparison.Ordinal)) return Errors.FileSystemManagement.InvalidPath; - // a segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories + // A segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories. if (sanitized.Contains('/') || sanitized.Contains('\\')) return Errors.FileSystemManagement.InvalidPath; if (sanitized.Length > MAX_DIRECTORY_SEGMENT_LENGTH) @@ -171,4 +171,21 @@ public class PathService : IPathService return newPathResult.Errors; return _platformContext.PathStrategy.GetPathRoot(newPathResult.Value); } + + /// + /// Checks whether is located inside . + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + public bool IsPathWithin(string path, string parentPath) + { + Result newPathResult = FileSystemPathId.Create(path); + if (newPathResult.IsFailure) + return false; + Result parentPathResult = FileSystemPathId.Create(parentPath); + if (parentPathResult.IsFailure) + return false; + return _platformContext.PathStrategy.IsPathWithin(newPathResult.Value, parentPathResult.Value); + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs index 08b46525..52897771 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs @@ -56,24 +56,24 @@ public class ThumbnailService : IThumbnailService /// An containing either a collection of bytes representing the thumbnail of the file at the specified path or an error. public async Task> GetThumbnailAsync(FileSystemPathId path, int quality, CancellationToken cancellationToken) { - // first, get the type of the image file + // First, get the type of the image file. Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(path, cancellationToken); if (imageTypeResult.IsFailure) return imageTypeResult.Errors; if (imageTypeResult.Value != ImageType.None) { - // then, get its bytes + // Then, get its bytes. Result resultFileContents = _environmentContext.FileProviderService.GetFileAsync(path); if (resultFileContents.IsFailure) return resultFileContents.Errors; byte[] fileContents = resultFileContents.Value; - // finally, resize or adjust quality based on image type - byte[]? adjustedImage = null; + // Finally, resize or adjust the quality based on the image type. + Optional adjustedImage = Optional.None(); if (imageTypeResult.Value is ImageType.JPEG or ImageType.JPEG_CANON or ImageType.JPEG2000 or ImageType.JPEG_UNKNOWN or ImageType.PNG or ImageType.BMP or ImageType.WEBP or ImageType.GIF or ImageType.TIFF or ImageType.TGA) - adjustedImage = await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken); - return new Thumbnail(imageTypeResult.Value, adjustedImage ?? fileContents); + adjustedImage = Optional.Some(await AdjustImageResolutionAsync(fileContents, imageTypeResult.Value, quality, cancellationToken)); + return new Thumbnail(imageTypeResult.Value, adjustedImage.HasValue ? adjustedImage.Value : fileContents); } else return Errors.Thumbnails.NoThumbnail; @@ -105,7 +105,7 @@ public class ThumbnailService : IThumbnailService case ImageType.PNG: { using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); - // PNG is lossless; quality adjustments don't apply in the same way - we can adjust compression + // PNG is lossless, so quality adjustments do not apply in the same way; instead, the compression level is adjusted. int compressionLevel = MapRange(quality, 1, 100, 1, 9); PngEncoder encoder = new() { CompressionLevel = (PngCompressionLevel)compressionLevel }; @@ -115,11 +115,11 @@ public class ThumbnailService : IThumbnailService case ImageType.BMP: { using Image image = await Image.LoadAsync(inputMemoryStream, cancellationToken); - await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // convert BMP to PNG for compression + await image.SaveAsync(outputMemoryStream, new PngEncoder(), cancellationToken); // Convert BMP to PNG for compression. break; } default: - return imageBytes; // for unsupported formats, just return the original bytes + return imageBytes; // For unsupported formats, just return the original bytes. } return outputMemoryStream.ToArray(); } @@ -140,7 +140,7 @@ public class ThumbnailService : IThumbnailService double ratio = quality / 100.0; int newWidth = (int)(image.Width * ratio); int newHeight = (int)(image.Height * ratio); - // ensure new dimensions are not zero + // Ensure the new dimensions are not zero. newWidth = Math.Max(1, newWidth); newHeight = Math.Max(1, newHeight); ResizeOptions options = new() @@ -148,9 +148,9 @@ public class ThumbnailService : IThumbnailService Size = new Size(newWidth, newHeight), Mode = ResizeMode.Max }; - // resize the image to the specified size + // Resize the image to the specified size. image.Mutate(ctx => ctx.Resize(options)); - // save the resized image and return its bytes + // Save the resized image and return its bytes. switch (imageType) { case ImageType.BMP: @@ -166,7 +166,7 @@ public class ThumbnailService : IThumbnailService await image.SaveAsync(outputMemoryStream, image.Metadata.DecodedImageFormat!, cancellationToken); break; default: - return imageBytes; // for unsupported formats, just return the original bytes + return imageBytes; // For unsupported formats, just return the original bytes. } return outputMemoryStream.ToArray(); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index 2d36653b..ecc0e00a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -24,9 +24,9 @@ public interface IPathStrategy /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - bool Exists(FileSystemPathId path, bool includeHiddenElements = true); + bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true); /// /// Tries to combine with . @@ -68,4 +68,12 @@ public interface IPathStrategy /// The path for which to get the root. /// An containing the root of , or an error. Result GetPathRoot(FileSystemPathId path); + + /// + /// Checks whether is located inside . + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 2b6039e5..0f2f6010 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -37,11 +37,11 @@ public class UnixPathStrategy : IUnixPathStrategy /// if is a valid path, otherwise. public bool IsValidPath(FileSystemPathId path) { - // check for invalid path characters + // Check for invalid path characters. char[] invalidChars = GetInvalidPathCharsForPlatform(); if (path.Path.IndexOfAny(invalidChars) >= 0) return false; - // check for relative paths + // Check for relative paths. if (path.Path.StartsWith("./") || path.Path.StartsWith("../")) return false; const string PATH_PATTERN = @"^\/([\w\-\.\~!$&'()*+,;=:@\[\] ]+(\/[\w\-\.\~!$&'()*+,;=:@\[\] ]+)*)?\/?$"; @@ -52,9 +52,9 @@ public class UnixPathStrategy : IUnixPathStrategy /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - public bool Exists(FileSystemPathId path, bool includeHiddenElements = true) + public bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true) { if (!_fileSystem.Path.Exists(path.Path)) return false; @@ -69,9 +69,9 @@ public class UnixPathStrategy : IUnixPathStrategy IFileInfo fileInfo = _fileSystem.FileInfo.New(path.Path); isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; } - else // path exists but is neither a file nor a directory (drive, etc) + else // The path exists but is neither a file nor a directory (drive, etc.). return true; - return includeHiddenElements || !isHidden; + return shouldIncludeHiddenElements || !isHidden; } /// @@ -84,11 +84,11 @@ public class UnixPathStrategy : IUnixPathStrategy { if (string.IsNullOrWhiteSpace(name)) return Errors.FileSystemManagement.NameCannotBeEmpty; - // trim any directory separator characters from the end of the path + // Trim any directory separator characters from the end of the path. string subpath = path.Path.TrimEnd(PathSeparator); - // if the name begins with a directory separator, remove it + // If the name begins with a directory separator, remove it. name = name.TrimStart(PathSeparator); - // combine the two parts with the Unix directory separator character + // Combine the two parts with the Unix directory separator character. return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator); } @@ -99,20 +99,20 @@ public class UnixPathStrategy : IUnixPathStrategy /// An containing the path segments, or an error. public Result> ParsePath(FileSystemPathId path) { - // if path starts with anything other than '/', it's considered relative and invalid for this parser + // If the path starts with anything other than '/', it is considered relative and invalid for this parser. if (!path.Path.StartsWith(PathSeparator)) return Errors.FileSystemManagement.InvalidPath; - // get the path segments + // Get the path segments. List splitSegments = [.. path.Path.Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries)]; IEnumerable> segmentsResults = splitSegments.Select((segment, index) => { bool isDirectory; if (segment.Contains('.')) - isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the path ends with a '/' + isDirectory = index != splitSegments.Count - 1 || path.Path.EndsWith(PathSeparator); // Check if it is the last segment or if the path ends with a '/'. else isDirectory = true; return PathSegment.Create(segment, isDirectory, isDrive: false); - }).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as "root drive" + }).Prepend(PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true)); // UNIX paths have '/' as their "root drive". foreach (Result segment in segmentsResults) if (segment.IsFailure) return segment.Errors; @@ -126,19 +126,19 @@ public class UnixPathStrategy : IUnixPathStrategy /// An containing the path segments of the path up one level from , or an error. public Result> GoUpOneLevel(FileSystemPathId path) { - // validation: ensure the path is not null or empty + // Validation: ensure the path is not null or empty. if (!IsValidPath(path)) return Errors.FileSystemManagement.InvalidPath; - // trim trailing slash for consistent processing + // Trim the trailing slash for consistent processing. string tempPath = path.Path; if (tempPath.EndsWith('/')) tempPath = tempPath.TrimEnd(PathSeparator); - // find the last occurrence of a slash + // Find the last occurrence of a slash. int lastIndex = tempPath.LastIndexOf(PathSeparator); - // if there's no slash found (shouldn't happen due to previous steps), or if we are at the root level after trimming, return error + // If no slash is found (which should not happen after the previous steps), or if we are at the root level after trimming, return an error. if (lastIndex < 0) return Errors.FileSystemManagement.CannotNavigateUp; - // return the path up to the last slash, or, if there's only the root slash, return that one instead + // Return the path up to the last slash, or, if there is only the root slash, return that one instead. Result newPathResult = FileSystemPathId.Create(lastIndex > 0 ? tempPath[..lastIndex] : tempPath[..1]); if (newPathResult.IsFailure) return newPathResult.Errors; @@ -148,7 +148,7 @@ public class UnixPathStrategy : IUnixPathStrategy /// /// Returns a collection of characters that are invalid for paths. /// - /// A collection of characters that are invalid in the context of paths + /// A collection of characters that are invalid in the context of paths. public char[] GetInvalidPathCharsForPlatform() { return ['\0']; @@ -173,9 +173,52 @@ public class UnixPathStrategy : IUnixPathStrategy if (!IsValidPath(path)) return Errors.FileSystemManagement.InvalidPath; - // On Unix-like systems, the root is always "/" + // On Unix-like systems, the root is always "/". if (path.Path.StartsWith(PathSeparator)) return PathSegment.Create(PathSeparator.ToString(), isDirectory: false, isDrive: true); return Errors.FileSystemManagement.InvalidPath; } + + /// + /// Checks whether is located inside . The comparison resolves the "." and ".." + /// segments first, so that a path can never escape its parent through relative segments, and it is case-sensitive, because + /// Unix paths are case-sensitive. + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + public bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath) + { + string[] pathSegments = NormalizePathSegments(path.Path); + string[] parentPathSegments = NormalizePathSegments(parentPath.Path); + if (parentPathSegments.Length == 0 || pathSegments.Length <= parentPathSegments.Length) + return false; + for (int index = 0; index < parentPathSegments.Length; index++) + if (!string.Equals(pathSegments[index], parentPathSegments[index], StringComparison.Ordinal)) + return false; + return true; + } + + /// + /// Splits into its segments, resolving the "." (current directory) and ".." (parent directory) segments. + /// + /// The path to be normalized. + /// The normalized path segments of the path. + private string[] NormalizePathSegments(string path) + { + List segments = []; + foreach (string segment in path.Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries)) + { + if (segment == ".") + continue; + if (segment == "..") + { + if (segments.Count > 0) + segments.RemoveAt(segments.Count - 1); + continue; + } + segments.Add(segment); + } + return [.. segments]; + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 396dee6f..efb203ca 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -37,12 +37,12 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// if is a valid path, otherwise. public bool IsValidPath(FileSystemPathId path) { - // check for invalid path characters + // Check for invalid path characters. char[] invalidChars = GetInvalidPathCharsForPlatform(); if (path.Path.IndexOfAny(invalidChars) >= 0) return false; - // regular expression to match valid absolute paths - // this allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share) + // Regular expression to match valid absolute paths. + // This allows drive letters (e.g., C:\) and UNC paths (e.g., \\server\share). const string PATH_PATTERN = @"^(?:[a-zA-Z]:\\|\\\\[a-zA-Z0-9\s()._&+,\[\]-]+\\[a-zA-Z0-9\s()._&+,\[\]-]+)(?:[a-zA-Z0-9\s()._&+,\[\]-]+\\)*[a-zA-Z0-9\s()._&+,\[\]-]*\\?$"; return Regex.IsMatch(path.Path, PATH_PATTERN); } @@ -51,9 +51,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// Checks if exists. /// /// The path to be checked. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// if exists, otherwise. - public bool Exists(FileSystemPathId path, bool includeHiddenElements = true) + public bool Exists(FileSystemPathId path, bool shouldIncludeHiddenElements = true) { if (!_fileSystem.Path.Exists(path.Path)) return false; @@ -68,9 +68,9 @@ public class WindowsPathStrategy : IWindowsPathStrategy IFileInfo fileInfo = _fileSystem.FileInfo.New(path.Path); isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; } - else // path exists but is neither a file nor a directory (drive, etc) + else // The path exists but is neither a file nor a directory (drive, etc.). return true; - return includeHiddenElements || !isHidden; + return shouldIncludeHiddenElements || !isHidden; } /// @@ -81,13 +81,13 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// An containing the combined path, or an error. public Result CombinePath(FileSystemPathId path, string name) { - if (name == null) + if (string.IsNullOrWhiteSpace(name)) return Errors.FileSystemManagement.NameCannotBeEmpty; - // trim any directory separator characters from the end of the path + // Trim any directory separator characters from the end of the path. string subpath = path.Path.TrimEnd(PathSeparator); - // if the name begins with a directory separator, remove it + // If the name begins with a directory separator, remove it. name = name.TrimStart(PathSeparator); - // combine the two parts with the Windows directory separator character + // Combine the two parts with the Windows directory separator character. return FileSystemPathId.Create(subpath + PathSeparator + name + PathSeparator); } @@ -98,7 +98,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// An containing the path segments, or an error. public Result> ParsePath(FileSystemPathId path) { - // Windows paths usually start with a drive letter and colon, e.g., "C:", or "\\" (UNC paths) + // Windows paths usually start with a drive letter and colon (e.g., "C:") or with "\\" (UNC paths). if (!(path.Path.StartsWith(@"\\") || (path.Path.Length >= 3 && char.IsLetter(path.Path[0]) && path.Path[1] == ':' && path.Path[2] == PathSeparator))) return Errors.FileSystemManagement.InvalidPath; IEnumerable> getPathSegmentsResults = GetPathSegments(); @@ -110,25 +110,25 @@ public class WindowsPathStrategy : IWindowsPathStrategy { if (path.Path.StartsWith(@"\\")) { - // handle UNC path + // Handle a UNC path. yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true); string[] segments = path.Path[2..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < segments.Length; i++) yield return CreatePathSegment(segments[i], i, segments.Length); } - else // handle regular Windows path + else // Handle a regular Windows path. { - // the drive segment + // The drive segment. yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true); - // extract the other segments + // Extract the other segments. string[] segments = path.Path[3..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < segments.Length; i++) { string segment = segments[i]; bool isDirectory; if (segment.Contains('.')) - isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // check if it's the last segment or if the next segment also contains a path delimiter + isDirectory = i != segments.Length - 1 || path.Path.EndsWith(PathSeparator); // Check if it is the last segment, or if the next segment also contains a path delimiter. else isDirectory = true; yield return PathSegment.Create(segment, isDirectory, isDrive: false); @@ -151,29 +151,29 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// An containing the path segments of the path up one level from , or an error. public Result> GoUpOneLevel(FileSystemPathId path) { - // validation: ensure the path is not null or empty + // Validation: ensure the path is not null or empty. if (!IsValidPath(path)) return Errors.FileSystemManagement.InvalidPath; - // trim trailing backslash for consistent processing + // Trim the trailing backslash for consistent processing. string tempPath = path.Path.TrimEnd(PathSeparator); - // check for UNC path + // Check for a UNC path. if (tempPath.StartsWith(@"\\")) { string[] parts = tempPath.Split(PathSeparator, StringSplitOptions.RemoveEmptyEntries); if (parts.Length <= 2) return Errors.FileSystemManagement.CannotNavigateUp; - // if it's a single-level UNC path, return the UNC root + // If it is a single-level UNC path, return the UNC root. if (parts.Length == 3) return ParsePath(FileSystemPathId.Create($@"\\{parts[0]}\{parts[1]}").Value); - } // check for drive root (both with and without trailing backslash) + } // Check for the drive root, both with and without a trailing backslash. else if ((tempPath.Length == 2 && tempPath[1] == ':') || (tempPath.Length == 3 && tempPath[1] == ':' && tempPath[2] == PathSeparator)) return Errors.FileSystemManagement.CannotNavigateUp; - // find the last occurrence of a backslash + // Find the last occurrence of a backslash. int lastIndex = tempPath.LastIndexOf(PathSeparator); - // if there's no backslash found or it's at the root level, return the root + // If no backslash is found or it is at the root level, return the root. if (lastIndex <= 2) return ParsePath(FileSystemPathId.Create(tempPath[..3]).Value); - // return the path up to the last backslash + // Return the path up to the last backslash. Result newPathResult = FileSystemPathId.Create(tempPath[..lastIndex]); if (newPathResult.IsFailure) return newPathResult.Errors; @@ -184,7 +184,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy /// /// Returns a collection of characters that are invalid for paths. /// - /// A collection of characters that are invalid in the context of paths + /// A collection of characters that are invalid in the context of paths. public char[] GetInvalidPathCharsForPlatform() { return ['<', '>', '"', '/', '|', '?', '*']; @@ -208,28 +208,71 @@ public class WindowsPathStrategy : IWindowsPathStrategy { if (!IsValidPath(path)) return Errors.FileSystemManagement.InvalidPath; - // handle UNC paths (e.g., \\server\share\folder) + // Handle UNC paths (e.g., \\server\share\folder). if (path.Path.StartsWith(@"\\")) { - // find the position of the second backslash (after \\server) + // Find the position of the second backslash (after \\server). int secondBackslash = path.Path.IndexOf('\\', 2); if (secondBackslash == -1) - return Errors.FileSystemManagement.InvalidPath; // invalid UNC path, missing server name - // find the position of the third backslash (after \\server\share) + return Errors.FileSystemManagement.InvalidPath; // Invalid UNC path, missing server name. + // Find the position of the third backslash (after \\server\share). int thirdBackslash = path.Path.IndexOf('\\', secondBackslash + 1); if (thirdBackslash == -1) - thirdBackslash = path.Path.Length; // no third backslash, use entire path - // return the UNC root (\\server\share\) + thirdBackslash = path.Path.Length; // No third backslash, use the entire path. + // Return the UNC root (\\server\share\). return PathSegment.Create(path.Path[..thirdBackslash] + "\\", isDirectory: true, isDrive: false); } - else // handle drive letter paths (e.g., C:\folder) - // check if the path starts with a drive letter followed by a colon (e.g., C:) - // path.Path.Length >= 2: Ensure the path is at least 2 characters long - // char.IsLetter(path.Path[0]): First character should be a letter - // path.Path[1] == ':': Second character should be a colon + else // Handle drive letter paths (e.g., C:\folder). + // Check if the path starts with a drive letter followed by a colon (e.g., C:). + // The path must be at least 2 characters long. + // The first character must be a letter. + // The second character must be a colon. if (path.Path.Length >= 2 && char.IsLetter(path.Path[0]) && path.Path[1] == ':') - return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // return the drive root (e.g., C:\) - // if we reach here, the path is neither a valid UNC path nor a valid drive path + return PathSegment.Create(path.Path[..2] + "\\", isDirectory: true, isDrive: true); // Return the drive root (e.g., C:\). + // If we reach here, the path is neither a valid UNC path nor a valid drive path. return Errors.FileSystemManagement.InvalidPath; } + + /// + /// Checks whether is located inside . The comparison resolves the "." and ".." + /// segments first, so that a path can never escape its parent through relative segments, and it is case-insensitive, because + /// Windows paths are case-insensitive. + /// + /// The path to be checked. + /// The path that must contain the checked path. + /// if the path is inside the parent path, otherwise. + public bool IsPathWithin(FileSystemPathId path, FileSystemPathId parentPath) + { + string[] pathSegments = NormalizePathSegments(path.Path); + string[] parentPathSegments = NormalizePathSegments(parentPath.Path); + if (parentPathSegments.Length == 0 || pathSegments.Length <= parentPathSegments.Length) + return false; + for (int index = 0; index < parentPathSegments.Length; index++) + if (!string.Equals(pathSegments[index], parentPathSegments[index], StringComparison.OrdinalIgnoreCase)) + return false; + return true; + } + + /// + /// Splits into its segments, resolving the "." (current directory) and ".." (parent directory) segments. + /// + /// The path to be normalized. + /// The normalized path segments of the path. + private string[] NormalizePathSegments(string path) + { + List segments = []; + foreach (string segment in path.Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries)) + { + if (segment == ".") + continue; + if (segment == "..") + { + if (segments.Count > 0) + segments.RemoveAt(segments.Count - 1); + continue; + } + segments.Add(segment); + } + return [.. segments]; + } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs index 34f5b47a..b72a8b1e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Platform/PlatformContextManager.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Runtime.InteropServices; @@ -11,7 +12,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// public class PlatformContextManager : IPlatformContextManager { - private IPlatformContext? _currentPlatformContext; + private Optional _currentPlatformContext; private readonly IPlatformContextFactory _platformContextFactory; private readonly IOperatingSystemInfo _operatingSystemInfo; @@ -32,13 +33,13 @@ public class PlatformContextManager : IPlatformContextManager /// The current platform context. public IPlatformContext GetCurrentContext() { - // set a default context if none is set - if (_currentPlatformContext is null) + // Set a default context if none is set. + if (!_currentPlatformContext.HasValue) if (_operatingSystemInfo.IsOSPlatform(OSPlatform.Linux) || _operatingSystemInfo.IsOSPlatform(OSPlatform.OSX)) SetCurrentPlatform(PlatformType.Unix); else SetCurrentPlatform(PlatformType.Windows); - return _currentPlatformContext!; + return _currentPlatformContext.Value; } /// @@ -48,12 +49,12 @@ public class PlatformContextManager : IPlatformContextManager /// Thrown when an unsupported platform type is provided. public void SetCurrentPlatform(PlatformType platformType) { - // determine the correct context based on platformType - _currentPlatformContext = platformType switch + // Determine the correct context based on the platform type. + _currentPlatformContext = Optional.Some(platformType switch { PlatformType.Unix => _platformContextFactory.CreateStrategy(), PlatformType.Windows => _platformContextFactory.CreateStrategy(), _ => throw new ArgumentException($"Unsupported platform type: {platformType}"), - }; + }); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs index 9e771528..7701b22a 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/ValueObjects/StreamInfo.cs @@ -2,7 +2,6 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Models.Core; - using System.Collections.Generic; using System.Diagnostics; #endregion @@ -110,9 +109,9 @@ public class StreamInfo : ValueObject Optional sampleRate, Optional channels) { - if (streamId is null) + if (string.IsNullOrWhiteSpace(streamId)) return Errors.FileSystemManagement.StreamIdCannotBeEmpty; - if (codec is null) + if (string.IsNullOrWhiteSpace(codec)) return Errors.FileSystemManagement.CodecCannotBeEmpty; if (bitrate <= 0) return Errors.FileSystemManagement.BitrateMustBeAPositiveNumber; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index c49151d9..91d8ee8f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -43,12 +43,12 @@ public class Library : AggregateRoot /// /// Gets the path of the image file used as the cover for the library. /// - public string? CoverImage { get; private set; } + public Optional CoverImage { get; private set; } /// /// Gets the path of the image file chosen by the user to be used as the cover for the library. /// - public string? CoverImageSourcePath { get; private set; } + public Optional CoverImageSourcePath { get; private set; } /// /// Gets whether this media library is enabled or not. A disabled media library is never shown or changed. @@ -107,7 +107,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, List contentLocations, - string? coverImage, + Optional coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, @@ -150,7 +150,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, IEnumerable contentLocations, - string? coverImageSourcePath, + Optional coverImageSourcePath, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, @@ -159,7 +159,7 @@ public class Library : AggregateRoot List scanIds) { List tempContentLocations = []; - // go through all the file system paths that make up the media library and create domain objects from them + // Go through all the file system paths that make up the media library and create domain objects from them. foreach (string contentLocation in contentLocations) { Result contentLocationResult = FileSystemPathId.Create(contentLocation); @@ -207,7 +207,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, IEnumerable contentLocations, - string? coverImageSourcePath, + Optional coverImageSourcePath, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, @@ -216,7 +216,7 @@ public class Library : AggregateRoot List scanIds) { List tempContentLocations = []; - // go through all the file system paths that make up the media library and create domain objects from them + // Go through all the file system paths that make up the media library and create domain objects from them. foreach (string contentLocation in contentLocations) { Result contentLocationResult = FileSystemPathId.Create(contentLocation); @@ -254,7 +254,7 @@ public class Library : AggregateRoot /// The internal libray path location of the cover image file. public void SetInternalLibraryCoverImagePath(string path) { - CoverImage = path; + CoverImage = Optional.Some(path); } /// @@ -263,14 +263,14 @@ public class Library : AggregateRoot /// An representing either a successful operation, or an error. public Result Delete() { - // clear all existing events since they become irrelevant when the entity is deleted, and they dont need to be processed + // Clear all existing events, since they become irrelevant when the entity is deleted and do not need to be processed. _domainEvents.Clear(); - // only add the delete event if it hasn't been added already + // Only add the delete event if it has not been added already. if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent)) _domainEvents.Add(new LibraryDeletedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); - // TODO: perhaps trigger events for removing contents related to the removed library (media metadata, etc)? + // TODO: Perhaps trigger events for removing content related to the removed library (media metadata, etc.). return Result.Deleted; } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs index 103ce5f8..588440d1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs @@ -1,5 +1,6 @@ #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.LibraryScanAggregate.ValueObjects; using System; @@ -22,5 +23,5 @@ public record LibraryScanFailedDomainEvent( LibraryId LibraryId, MediaLibraryScanCompositeId MediaLibraryScanCompositeId, DateTime OccurredOnUtc, - string? ErrorMessage = null + Optional ErrorMessage ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs deleted file mode 100644 index 80ba5336..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRole.cs +++ /dev/null @@ -1,65 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Models.Core; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; - -/// -/// Value Object for the role of a media contributor in a media item. -/// The role carries both a free-form display name, as returned by the metadata providers, and the canonical -/// category the display name normalizes to, so that roles describing the same kind of contribution are never -/// treated as distinct. -/// -[DebuggerDisplay("{DisplayName}")] -public sealed class MediaContributorRole : ValueObject -{ - /// - /// Gets the display name of the role. - /// - public string DisplayName { get; } - - /// - /// Gets the canonical category of the role. - /// - public MediaContributorRoleCategory Category { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The display name of the role. - /// The canonical category of the role. - private MediaContributorRole(string displayName, MediaContributorRoleCategory category) - { - DisplayName = displayName; - Category = category; - } - - /// - /// Creates a new instance of the class, from a display and its canonical . - /// - /// The display name of the role. - /// The canonical category of the role. - /// The created instance. - public static Result Create(string displayName, MediaContributorRoleCategory category) - { - if (string.IsNullOrWhiteSpace(displayName)) - return Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty; - - return new MediaContributorRole(displayName, category); - } - - /// - /// Gets the list of items that define equality of the object. - /// - /// A list of items defining the equality. - public override IEnumerable GetEqualityComponents() - { - yield return DisplayName; - yield return Category; - } -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs index 5823ebb5..b0091621 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadata.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; -using System; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -72,7 +71,7 @@ public class VideoMetadata : BaseMetadata : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) { DurationInSeconds = durationInSeconds; - Resolution = resolution ?? throw new ArgumentNullException(nameof(resolution)); + Resolution = resolution; FrameRate = frameRate; VideoCodec = videoCodec; AudioCodec = audioCodec; diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index e46c330e..9f4ccca6 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; @@ -19,7 +18,7 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext [DebuggerDisplay("Id: {Id} Title: {Title}")] public sealed class Book : AggregateRoot { - private readonly List _contributors; + private readonly HashSet _contributors; private readonly List _ratings; private readonly List _isbns; @@ -109,12 +108,10 @@ public sealed class Book : AggregateRoot public IReadOnlyCollection ISBNs => _isbns.AsReadOnly(); /// - /// Gets the list of objects representing the unique identifiers of the media contributors (actors, directors, etc) starring in this book. + /// Gets the list of media contributors that contributed to this book, each carrying the role + /// the contributor played, used as the key of its localized display string. /// - public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); - // TODO: the roles of the media contributors currently live only in the persistence layer (BookContributorEntity), and are lost - // at the domain level. To keep consistency with the Music aggregate, which models its credits as a MediaContributorCredit value - // object carrying both the contributor and the role, the roles should be moved into the Book aggregate as well. + public IReadOnlyCollection Contributors => _contributors.AsReadOnly(); /// /// Gets the list of ratings for this book. @@ -144,7 +141,7 @@ public sealed class Book : AggregateRoot /// The date and time when the entity was created. /// The date and time when the entity was last updated. /// The list of ISBNs of the book. - /// The list of objects representing the unique identifiers of the media contributors of the book. + /// The list of media contributors of the book, each carrying the role the contributor played. /// The list of ratings for the book. private Book( BookId id, @@ -167,7 +164,7 @@ public sealed class Book : AggregateRoot DateTime createdOnUtc, Optional updatedOnUtc, List isbns, - List contributors, + IEnumerable contributors, List ratings) : base(id) { Id = id; @@ -188,9 +185,9 @@ public sealed class Book : AggregateRoot BarnesAndNobleId = barnesAndNobleId; AppleBooksId = appleBooksId; CreatedOnUtc = createdOnUtc; - UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null; + UpdatedOnUtc = updatedOnUtc; _isbns = isbns; - _contributors = contributors; + _contributors = [.. contributors]; _ratings = ratings; } @@ -214,7 +211,7 @@ public sealed class Book : AggregateRoot /// The optional Barnes & Noble ID of the book. /// The optional Apple Books ID of the book. /// The list of ISBNs of the book. - /// The list of objects representing the unique identifiers of the media contributors of the book. + /// The list of media contributors of the book, each carrying the role the contributor played. /// The list of ratings for the book. /// /// An containing either a successfully created , or an error message. @@ -237,10 +234,10 @@ public sealed class Book : AggregateRoot Optional barnesAndNobleId, Optional appleBooksId, List isbns, - List contributors, + IEnumerable contributors, List ratings) { - // TODO: enforce invariants + // TODO: enforce invariants. return new Book( BookId.CreateUnique(), libraryId, @@ -259,7 +256,7 @@ public sealed class Book : AggregateRoot googleBooksId, barnesAndNobleId, appleBooksId, - DateTime.UtcNow, // TODO: should be IDateTimeProvider + DateTime.UtcNow, // TODO: should be IDateTimeProvider. default, isbns, contributors, @@ -290,7 +287,7 @@ public sealed class Book : AggregateRoot /// The date and time when the entity was created. /// The date and time when the entity was last updated. /// The list of ISBNs of the book. - /// The list of objects representing the unique identifiers of the media contributors of the book. + /// The list of media contributors of the book, each carrying the role the contributor played. /// The list of ratings for the book. /// /// An containing either a successfully created , or an error message. @@ -316,10 +313,10 @@ public sealed class Book : AggregateRoot DateTime createdOnUtc, Optional updatedOnUtc, List isbns, - List contributors, + IEnumerable contributors, List ratings) { - // TODO: enforce invariants + // TODO: enforce invariants. return new Book( id, libraryId, @@ -347,14 +344,15 @@ public sealed class Book : AggregateRoot } /// - /// Replaces the media contributors of the book with the provided , identified by their unique identifiers. + /// Replaces the media contributors of the book with the provided , each carrying + /// the media contributor and the role the contributor played in the book. /// - /// The unique identifiers of the media contributors of the book. - public void UpdateContributors(IReadOnlyCollection contributors) + /// The media contributors of the book. + public void UpdateContributors(IReadOnlyCollection contributors) { - // replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate + // Replace the contents of the collection in place, preserving the readonly reference invariants of the aggregate. _contributors.Clear(); - _contributors.AddRange(contributors); + _contributors.UnionWith(contributors); } /// @@ -408,7 +406,7 @@ public sealed class Book : AggregateRoot GoogleBooksId = googleBooksId; BarnesAndNobleId = barnesAndNobleId; AppleBooksId = appleBooksId; - // replace the contents of the collections in place, preserving the readonly reference invariants of the aggregate + // Replace the contents of the collections in place, preserving the readonly reference invariants of the aggregate. _isbns.Clear(); _isbns.AddRange(isbns); _ratings.Clear(); diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs deleted file mode 100644 index bf64219b..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs +++ /dev/null @@ -1,17 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System; -using System.Collections.Generic; -#endregion - -namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; - -/// -/// Service for managing book libraries. -/// -public sealed class BookLibraryService : IBookLibraryService -{ - /// - /// Gets the collection of books in the library. - /// - public ICollection Books => throw new NotImplementedException(); -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs deleted file mode 100644 index 91368260..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs +++ /dev/null @@ -1,25 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Collections.Generic; -#endregion - -namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; - -/// -/// Interface for the service for managing book libraries. -/// -public interface IBookLibraryService -{ - /// - /// Gets the collection of books in the library. - /// - ICollection Books { get; } - - // ICollection Series { get; } - - // void AddBook(Book book); - // void RemoveBook(Guid bookId); - // void AddSeries(BookSeries series); - // void RemoveSeries(Guid seriesId); - // Book GetBook(Guid bookId); - // BookSeries GetSeries(Guid seriesId); -} \ No newline at end of file diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs deleted file mode 100644 index 3373766c..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.Models.Core; -using System; -using System.Collections.Generic; -using System.Diagnostics; -#endregion - -namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; - -/// -/// Value Object for the Id of a book library. -/// -[DebuggerDisplay("{Value}")] -public sealed class BookLibraryId : EntityId // TODO: to be removed -{ - /// - /// Initializes a new instance of the class. - /// - /// The value representing this object. - private BookLibraryId(Guid value) : base(value) - { - } - - /// - /// Creates a new instance of the class. - /// - /// The created instance. - public static Result CreateUnique() - { - // TODO: enforce invariants - return new BookLibraryId(Guid.NewGuid()); - } - - /// - /// Creates a new instance of the class, from a pre-existing . - /// - /// The value used to create the instance. - /// The created instance. - public static Result Create(Guid value) - { - // TODO: enforce invariants - return new BookLibraryId(value); - } - - /// - /// Gets the list of items that define equality of the object. - /// - /// A list of items defining the equality. - public override IEnumerable GetEqualityComponents() - { - yield return Value; - } -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookMediaContributor.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookMediaContributor.cs new file mode 100644 index 00000000..bac6b8e2 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookMediaContributor.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Value Object for a media contributor of a book, carrying the role the contributor played. +/// The media contributor is identified only by its Id, duplicated from the Media Contributor bounded context, and the role is +/// the canonical role the contributor played, used as the key of its localized display string. +/// +[DebuggerDisplay("{Role}")] +public sealed class BookMediaContributor : ValueObject +{ + /// + /// Gets the unique identifier of the media contributor. + /// + public MediaContributorId ContributorId { get; } + + /// + /// Gets the role the contributor played. + /// + public MediaContributorRole Role { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The unique identifier of the media contributor. + /// The role the contributor played. + private BookMediaContributor(MediaContributorId contributorId, MediaContributorRole role) + { + ContributorId = contributorId; + Role = role; + } + + /// + /// Creates a new instance of the class. + /// + /// The unique identifier of the media contributor. + /// The role the contributor played. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(MediaContributorId contributorId, MediaContributorRole role) + { + return new BookMediaContributor(contributorId, role); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return ContributorId; + yield return Role; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs index 6a841213..ea8e3ded 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/Isbn.cs @@ -46,12 +46,12 @@ public sealed class Isbn : ValueObject /// The value representing this object. /// The format of the ISBN representing this object. /// The created instance. - public static Result Create(string? value, IsbnFormat format) + public static Result Create(string value, IsbnFormat format) { - // enforce invariants + // Enforce invariants. if (string.IsNullOrWhiteSpace(value)) return Errors.WrittenContent.IsbnValueCannotBeEmpty; - // remove hyphens and spaces, for validation + // Remove hyphens and spaces, for validation. string cleanedValue = Regex.Replace(value, @"[-\s]", string.Empty); switch (format) { @@ -78,7 +78,7 @@ public sealed class Isbn : ValueObject { if (!s_isbn10Regex.IsMatch(isbn)) return false; - // remove any hyphens or spaces + // Remove any hyphens or spaces. isbn = isbn.Replace("-", "").Replace(" ", "").ToUpper(); int sum = 0; for (int i = 0; i < 9; i++) @@ -100,7 +100,7 @@ public sealed class Isbn : ValueObject { if (!s_isbn13Regex.IsMatch(isbn)) return false; - // remove any hyphens or spaces + // Remove any hyphens or spaces. isbn = isbn.Replace("-", "").Replace(" ", ""); int sum = 0; for (int i = 0; i < 12; i++) diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorId.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorId.cs new file mode 100644 index 00000000..4cb22126 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; + +/// +/// Value Object for the Id of a media contributor, duplicated from the MediaContributor bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaContributorId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaContributorId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaContributorId CreateUnique() + { + return new MediaContributorId(Guid.NewGuid()); + } + + /// + /// Creates a new instance of the class, from a pre-existing . + /// + /// The value used to create the instance. + /// The created instance. + public static MediaContributorId Create(Guid value) + { + return new MediaContributorId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs index 2dfccb20..d635095b 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/AuthorizationService.cs @@ -45,15 +45,15 @@ public class AuthorizationService : IAuthorizationService /// if the user has the specified permission, otherwise. public async Task HasPermissionAsync(Guid userId, AuthorizationPermission permission, CancellationToken cancellationToken) { - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; - // check if the user has the permission directly + // Check if the user has the permission directly. if (getUserResult.Value.UserPermissions.Any(userPermission => userPermission.Permission.PermissionName == permission)) return true; - // check if any of the user's roles grant the permission + // Check if any of the user's roles grant the permission. return getUserResult.Value.UserRole?.Role.RolePermissions .Any(rolePermission => rolePermission.Permission.PermissionName == permission) == true; } @@ -67,7 +67,7 @@ public class AuthorizationService : IAuthorizationService /// if the user is in the specified role, otherwise. public async Task IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken) { - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; return getUserResult.Value.UserRole?.Role.RoleName == role; @@ -83,7 +83,7 @@ public class AuthorizationService : IAuthorizationService /// if the user satisfies the policy, otherwise. public async Task EvaluatePolicyAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy { - // resolve the authorization policy dynamically using the factory + // Resolve the authorization policy dynamically using the factory. IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy(); return await policy.EvaluateAsync(userId, context, cancellationToken).ConfigureAwait(false); } @@ -96,7 +96,7 @@ public class AuthorizationService : IAuthorizationService /// An containing either a , or an error. public async Task> GetUserAuthorizationAsync(Guid userId, CancellationToken cancellationToken) { - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure) return getUserResult.Errors; @@ -104,18 +104,18 @@ public class AuthorizationService : IAuthorizationService if (getUserResult.Value is null) return Errors.Users.UserDoesNotExist; - // get all roles + // Get all roles. string? role = getUserResult.Value.UserRole?.Role.RoleName; - // get direct user permissions + // Get direct user permissions. HashSet directPermissions = [.. getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission.PermissionName)]; - // get permissions from roles + // Get permissions from roles. HashSet? rolePermissions = getUserResult.Value.UserRole?.Role.RolePermissions .Select(rolePermission => rolePermission.Permission.PermissionName) .ToHashSet(); - // combine all permissions + // Combine all permissions. HashSet allPermissions = rolePermissions is not null ? [.. directPermissions.Union(rolePermissions)] : directPermissions; return new UserAuthorizationEntity diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs index 07f903a3..c3269050 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs @@ -40,15 +40,15 @@ public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy if (context is not LibraryOwnershipPolicyContext libraryContext) return false; - // admins can access any media library - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + // Admins can access any media library. + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; if (getUserResult.Value.UserRole?.Role.RoleName == "Admin") return true; - // regular users can only access the media libraries they own - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken).ConfigureAwait(false); + // Regular users can only access the media libraries they own. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getLibraryResult.IsFailure || getLibraryResult.Value is null) return false; return getLibraryResult.Value.UserId == userId; diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs index 474db2aa..719818c9 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/Over18/Over18Policy.cs @@ -41,11 +41,11 @@ public class Over18Policy : IOver18Policy /// if the policy evaluation succeeds, otherwise. public async Task EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken) { - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false); + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getUserResult.IsFailure || getUserResult.Value is null) return false; - // TODO: uncomment when Date of Birth is implemented for users registration + // TODO: uncomment when Date of Birth is implemented for users registration. //if (!getUserResult.Value.DateOfBirth.HasValue) // return false; diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs index 74b156ab..e88b8eb5 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTracker.cs @@ -14,7 +14,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellati internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancellationTracker, IDisposable { private readonly ConcurrentDictionary _runningScans = new(); - private bool _disposed; + private bool _isDisposed; /// /// Registers a new scan operation for tracking. @@ -72,7 +72,7 @@ internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancel /// public void Dispose() { - if (!_disposed) + if (!_isDisposed) { foreach (CancellationTokenSource scan in _runningScans.Values) { @@ -80,7 +80,7 @@ internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancel scan.Dispose(); } _runningScans.Clear(); - _disposed = true; + _isDisposed = true; } } } 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 af0d994a..31d7f468 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 @@ -33,7 +33,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// 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 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; @@ -62,30 +62,30 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // 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 + // 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // 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 + // 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: + // 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); - // 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 + // 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).ConfigureAwait(false); + 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 @@ -95,8 +95,8 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } } - // 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 + // 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) { @@ -118,7 +118,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } } - // when no artwork provider is available, the books must not be marked as failed to resolve, so the enrichment is skipped entirely + // 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(); @@ -129,7 +129,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - // set the initial progress of the scan job + // 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); @@ -138,7 +138,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob 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 + // 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) { @@ -151,7 +151,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob 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 + // 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); @@ -162,11 +162,11 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob await EnrichBookArtworkAsync(bookEntity, artworkProviders, bookArtworkService, fileHashService, libraryName, getAuthorsResult.Value, cancellationToken).ConfigureAwait(false); - // check if enough time has passed since last update + // 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 + // 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); @@ -174,24 +174,24 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } } - // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // 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); - } - + Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is 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) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); @@ -222,19 +222,17 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob /// 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 + // 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, mark the cover artwork of the book as failed to resolve - BookArtworkEntity? coverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + // 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.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); - } + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); else { coverArtwork.Status = ArtworkStatus.Failed; @@ -244,9 +242,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob return; } - BookArtworkEntity? existingCoverArtwork = bookEntity.BookArtwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover && artwork.Ordinal == 0); + 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 + // 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; @@ -262,11 +260,9 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob 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 + // A failing artwork storage must not prevent the book from being tracked as failed to resolve. if (existingCoverArtwork is null) - { - bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); - } + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Failed, null, 0, null, null)); else { existingCoverArtwork.Status = ArtworkStatus.Failed; @@ -276,7 +272,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob return; } - // for remote artwork, compute the content hash of the stored artwork, which is a copy of the resolved one + // 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('/', '\\')); @@ -284,9 +280,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } if (existingCoverArtwork is null) - { - bookEntity.BookArtwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); - } + bookEntity.Artwork.Add(CreateCoverArtworkEntity(bookEntity.Id, ArtworkStatus.Enriched, saveArtworkResult.Value, contentHash, resolvedArtwork.ProviderName, DateTime.UtcNow)); else { existingCoverArtwork.FileName = saveArtworkResult.Value; @@ -300,7 +294,7 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } else { - // the resolved artwork is identical to the stored one, so the stored artwork is kept and the book is marked as enriched + // 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; @@ -338,13 +332,13 @@ internal sealed class MediaLibraryScanArtworkEnrichmentJob : MediaLibraryScanJob } catch (Exception) { - // a failing artwork provider must not prevent the other providers from being tried + // 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 + // 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; 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 a861002a..7db6d886 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 @@ -4,7 +4,7 @@ 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.Books; +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; @@ -17,9 +17,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library 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; @@ -38,7 +41,7 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Commo /// 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 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; @@ -67,36 +70,36 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // 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 + // 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // 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 + // 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: + // 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); - // load the media library, whose setting determines whether the providers that require access to the web are used during the enrichment + // 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).ConfigureAwait(false); + 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 + // 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); @@ -112,7 +115,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo providers.AddRange(configuredProviders); } - // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing + // 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) { @@ -123,7 +126,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo 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 + // 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); @@ -131,7 +134,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - // set the initial progress of the scan job + // 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); @@ -140,11 +143,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo 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 + // 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 + // 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) { @@ -163,11 +166,11 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, unitOfWork.BookRepository, unitOfWork.MediaContributorRepository, contributorsByNormalizedName, cancellationToken).ConfigureAwait(false); - // check if enough time has passed since last update + // 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 + // 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); @@ -175,8 +178,10 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } } - // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // 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(); @@ -184,16 +189,14 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } } else - { _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value); - } - + Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is 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) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); @@ -224,7 +227,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo /// 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 + // Convert the book to a domain object. Result getBookResult = bookEntity.ToDomainEntity(); if (getBookResult.IsFailure) return; @@ -233,7 +236,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo 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 + 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, @@ -246,19 +249,20 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo if (resolvedMetadata is null) { - // no metadata provider returned usable metadata, mark the book as failed to enrich, keeping its previous metadata + // 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 + // 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 + // 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) @@ -266,25 +270,26 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo MediaContributorEntity contributorEntity = await FindOrCreateContributorAsync(mediaContributorRepository, contributorsByNormalizedName, contributor, cancellationToken).ConfigureAwait(false); - string roleName = contributor.Role?.Name ?? "Contributor"; - MediaContributorRoleCategory roleCategory = contributor.Role?.Category ?? MediaContributorRoleCategory.Other; + 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, - RoleName = roleName, - RoleCategory = roleCategory, + Role = role, CreatedOnUtc = DateTime.UtcNow, CreatedBy = Guid.Empty, UpdatedBy = null }); + domainContributors.Add(BookMediaContributor.Create(MediaContributorId.Create(contributorEntity.Id), role).Value); } - bookEntity.BookContributors.Clear(); - bookEntity.BookContributors.AddRange(linkedContributors); - book.UpdateContributors([.. linkedContributors.Select(linkedContributor => Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects.MediaContributorId.Create(linkedContributor.MediaContributorId))]); + 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 + // 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; @@ -340,7 +345,7 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } catch (Exception) { - // a failing metadata provider must not prevent the other providers from being tried + // A failing metadata provider must not prevent the other providers from being tried. } } return null; @@ -369,12 +374,12 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo 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 + // 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 + // A failing metadata provider must not prevent the other providers from being tried. } } 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 487e3e38..40b350c9 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 @@ -53,36 +53,36 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // 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 + // 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // 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 + // 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: + // 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); - // set the initial progress of the scan job, it's a 1 step job - invalidating the stale enrichment state + // Set the initial progress of the scan job; it is a single step job, invalidating the stale enrichment state. Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints - // are compared against the current provider configuration to detect whether it changed since the last scan - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + // Load the media library, whose web access setting determines the effective provider set, and whose stored fingerprints + // are compared against the current provider configuration to detect whether it changed since the last scan. + 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."); LibraryEntity library = getLibraryResult.Value; - // load the provider configurations of the media library, whose fingerprint is compared against the stored one + // 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) throw new InvalidOperationException(getMetadataConfigurationsResult.FirstError.Description); @@ -91,7 +91,7 @@ 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 of the books of the user is aggregated from multiple providers, when fields are missing. bool shouldAggregateMetadataWhenMissing = false; if (unitOfWork.UserSettingsRepository is not null) { @@ -102,7 +102,7 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; } - // compare the current fingerprints against the stored ones, resetting the enrichment state of the channel whose configuration + // 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); @@ -122,27 +122,29 @@ internal sealed class MediaLibraryScanProviderConfigurationInvalidationJob : Med throw new InvalidOperationException(resetArtworkResult.FirstError.Description); } - // store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. - // the library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository - // update action, whose clearing and re-adding of the owned content locations would drop them when the same tracked instance is passed + // Store the current fingerprints, so that the next scan can detect whether the provider configuration changed again. + // The library is already tracked by the change tracker, so the modifications are persisted directly, without going through the repository + // 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.UpdatedOnUtc = DateTime.UtcNow; library.UpdatedBy = Guid.NewGuid(); - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); - // increment the number of processed elements progress + // Increment the number of processed elements progress. publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is 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) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); 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 a00ae9ba..b78a12d1 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,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -52,17 +52,17 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed { try { - // increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel) + // 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 + // 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 - // processing that takes time, and would block the processing of scan jobs in the in-memory queue + // 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 + // 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: + // 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()!; @@ -70,27 +70,27 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium + // 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) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - // get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them + // Get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them. Result> getDeletedPathsResult = await unitOfWork.LibraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false); 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 books 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); - // apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan + // Apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan. Result applySnapshotSwapResult = await unitOfWork.LibraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false); 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 books 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); @@ -98,14 +98,14 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed throw new InvalidOperationException(resetEnrichmentStateResult.FirstError.Description); } - // raise a deletion event for every media library scan snapshot item that is no longer present on disk + // Raise a deletion event for every media library scan snapshot item that is no longer present on disk. foreach (string deletedPath in getDeletedPathsResult.Value) { cancellationToken.ThrowIfCancellationRequested(); 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 books of the media library 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); @@ -124,19 +124,21 @@ internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMed if (insertBookResult.IsFailure) throw new InvalidOperationException(insertBookResult.FirstError.Description); } - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); - // increment the number of processed elements progress + // Increment the number of processed elements progress. publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsFailure) throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); Status = LibraryScanJobStatus.Completed; - // when this job has no linked children, it's the last job in the directed acyclic job graph, and the scan is 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) await domainEventPublisher.PublishAsync(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); - // call each linked child with the obtained payload + // Call each linked child with the obtained payload. foreach (IMediaLibraryScanJob child in Children) await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs index cade5637..42f35c39 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs @@ -1,5 +1,6 @@ #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.LibraryScanAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -26,16 +27,16 @@ internal static class ScanFailurePublisher /// Cancellation token that can be used to stop the execution. public static async Task PublishAsync(IServiceScopeFactory serviceScopeFactory, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, Exception exception, CancellationToken cancellationToken) { - // failure reporting is best-effort, a failure to report the failure must not crash the job processing + // Failure reporting is best-effort, a failure to report the failure must not crash the job processing. try { await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope(); IDomainEventPublisher domainEventPublisher = asyncServiceScope.ServiceProvider.GetService()!; - await domainEventPublisher.PublishAsync(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false); + await domainEventPublisher.PublishAsync(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, Optional.FromNullable(exception.Message)), cancellationToken).ConfigureAwait(false); } catch { - // the failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails + // The failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails. } } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs index 59368ab4..05a909de 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -89,7 +89,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); // get the library from the repository - Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + 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."); @@ -188,7 +188,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF /// Discovers the book 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. - /// Whether to skip the directories whose last write time has not changed since the last scan, or not. + /// 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. @@ -201,7 +201,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF [MethodImpl(MethodImplOptions.AggressiveOptimization)] private async Task DiscoverContentLocationAsync( string rootDirectoryPath, - bool skipUnchangedDirectories, + bool shouldSkipUnchangedDirectories, Dictionary? fingerprintsByPath, List stagingBatch, List fingerprintBatch, @@ -220,7 +220,7 @@ internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksF DirectoryInfo 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 (skipUnchangedDirectories) + if (shouldSkipUnchangedDirectories) { DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc; if (fingerprintsByPath is not null && 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 efd252b3..1355aaff 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Artwork/BookArtworkService.cs @@ -115,12 +115,12 @@ internal sealed class BookArtworkService : IBookArtworkService // Copy the uploaded artwork into a temporary file, so that the shared artwork storage can validate and copy it. string temporaryPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}{Path.GetExtension(fileName)}"); - bool written = false; + bool isWritten = false; try { await using (FileStream fileStream = new(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true)) await artworkStream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); - written = true; + isWritten = true; } catch (OperationCanceledException) { @@ -133,7 +133,7 @@ internal sealed class BookArtworkService : IBookArtworkService finally { // Remove the partially written temporary file when the upload failed. - if (!written && File.Exists(temporaryPath)) + if (!isWritten && File.Exists(temporaryPath)) File.Delete(temporaryPath); } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Metadata/MetadataAggregator.cs similarity index 97% rename from src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Metadata/MetadataAggregator.cs index 85abe3e3..cc03db66 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Metadata/MetadataAggregator.cs @@ -5,7 +5,7 @@ using System; using System.Collections.Generic; #endregion -namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; /// /// Merges the book metadata returned by multiple metadata providers into a single book metadata, giving priority to the first provider that provides a value for each field. @@ -45,7 +45,7 @@ internal static class MetadataAggregator FirstOrDefaultReference(first.BarnesAndNobleId, second.BarnesAndNobleId), FirstOrDefaultReference(first.AppleBooksId, second.AppleBooksId), Union(first.Isbns, second.Isbns, isbn => isbn.Value), - Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role?.Name}"), + Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role}"), Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()), FirstOrDefaultReference(first.CoverImagePath, second.CoverImagePath)); } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index 19602b01..c31213fa 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; @@ -109,12 +111,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService // Remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status, // and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed. IMediaLibraryProviderConfigurationStore providerConfigurationStore = asyncServiceScope.ServiceProvider.GetRequiredService(); - Result> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false); + Result> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(cancellationToken: stoppingToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) _logger.LogError("Failed to get the detected plugins while reconciling the plugin rows."); else { - foreach (PluginEntity plugin in getPluginsResult.Value) + foreach (PluginEntity plugin in getPluginsResult.Value.Data) { if (detectedPluginIds.Contains(plugin.Id)) continue; @@ -128,12 +130,12 @@ internal sealed class PluginDetectionSyncJob : BackgroundService } // Seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type. - Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(stoppingToken).ConfigureAwait(false); + Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(cancellationToken: stoppingToken).ConfigureAwait(false); if (getLibrariesResult.IsFailure) _logger.LogError("Failed to get the media libraries while seeding the provider configurations."); else { - foreach (LibraryEntity library in getLibrariesResult.Value) + foreach (LibraryEntity library in getLibrariesResult.Value.Data) { Result ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); if (ensureResult.IsFailure) @@ -144,7 +146,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService } } - await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(stoppingToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); } /// diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs index eb897343..7e02ce87 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginInstaller.cs @@ -108,21 +108,21 @@ internal sealed class PluginInstaller : IPluginInstaller { using ZipArchive zipArchive = new(archive); Directory.CreateDirectory(_pluginsDirectory); - bool foundAssembly = false; + bool isAssemblyFound = false; foreach (ZipArchiveEntry entry in zipArchive.Entries) { cancellationToken.ThrowIfCancellationRequested(); string? safeFileName = GetSafeFileName(entry.FullName); if (safeFileName is null || !string.Equals(Path.GetExtension(safeFileName), ".dll", StringComparison.OrdinalIgnoreCase)) continue; - foundAssembly = true; + isAssemblyFound = true; string destinationPath = Path.Combine(_pluginsDirectory, safeFileName); await using Stream entryStream = entry.Open(); await using FileStream outputStream = new(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None); await entryStream.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false); } - if (!foundAssembly) + if (!isAssemblyFound) return Errors.Plugins.PluginArchiveContainsNoAssemblies; return Result.Success; } @@ -135,8 +135,8 @@ internal sealed class PluginInstaller : IPluginInstaller /// The bare file name, or when the path contains no usable file name. private static string? GetSafeFileName(string path) { - // a backslash is not a directory separator on non-Windows platforms, so it is normalized to '/' first, - // after which Path.GetFileName can strip any directory component on every platform + // A backslash is not a directory separator on non-Windows platforms, so it is normalized to '/' first, + // after which Path.GetFileName can strip any directory component on every platform. string fileName = Path.GetFileName(path.Replace('\\', '/')); return fileName is "" or "." or ".." ? null : fileName; } diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs index 149acff8..75aa4ff8 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginSettingsStore.cs @@ -41,7 +41,7 @@ internal sealed class PluginSettingsStore : IPluginSettingsStore /// The persisted settings keyed by setting key, or when no settings were persisted for the plugin. public async Task?> GetSettingsAsync(Guid pluginId, CancellationToken cancellationToken) { - Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(pluginId, cancellationToken: cancellationToken).ConfigureAwait(false); if (getPluginResult.IsFailure) { _logger.LogWarning("Failed to read the settings of the plugin with Id '{PluginId}': {Error}", pluginId, getPluginResult.FirstError.Description); diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs index 15511ac3..968685da 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/ScheduledJobSchedulerJob.cs @@ -68,7 +68,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// A task that represents the asynchronous operation. public Task StartCycleAsync(ScheduledJobId scheduledJobId, CancellationToken cancellationToken) { - RunCycleWorkerAsync(scheduledJobId, runImmediately: true, cancellationToken).FireAndForgetSafeAsync(); + RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately: true, cancellationToken).FireAndForgetSafeAsync(); return Task.CompletedTask; } @@ -174,8 +174,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS continue; } // A once at startup scheduled job fires immediately when its cycle is resumed at startup; the other scheduled jobs wait for their next scheduled execution. - bool runImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup; - RunCycleWorkerAsync(scheduledJobId, runImmediately, cancellationToken).FireAndForgetSafeAsync(); + bool shouldRunImmediately = scheduledJob.ScheduleType == ScheduleType.OnceAtStartup; + RunCycleWorkerAsync(scheduledJobId, shouldRunImmediately, cancellationToken).FireAndForgetSafeAsync(); } } @@ -183,9 +183,9 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS /// Runs the execution cycle worker of the scheduled job identified by . /// /// The object representing the unique identifier of the scheduled job whose cycle is run. - /// Whether the task of the scheduled job is run immediately when the cycle starts. + /// Whether the task of the scheduled job is run immediately when the cycle starts. /// Cancellation token that can be used to stop the execution. - private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool runImmediately, CancellationToken stoppingToken) + private async Task RunCycleWorkerAsync(ScheduledJobId scheduledJobId, bool shouldRunImmediately, CancellationToken stoppingToken) { // Each cycle owns its own cancellation token source: it is the handle the runtime registry stores, so stopping one // scheduled job cancels exactly this cycle and no other job's cycle, even though the cycle worker itself runs "fire and forget" on another thread. @@ -203,7 +203,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS CancellationToken cycleToken = linkedCancellationTokenSource.Token; // An immediate run is executed as a cycle run, so it completes the scheduled job back to its active state and is // recorded as part of the cycle; this is the path taken by an admin start, by the resume at startup and by the seed of the default jobs. - if (runImmediately) + if (shouldRunImmediately) await RunScheduledJobAsync(scheduledJobId, isCycleRun: true, cycleToken).ConfigureAwait(false); // The schedule is read from the storage medium for every cycle, so the delay until the next run is always @@ -320,7 +320,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS IDomainEventPublisher domainEventPublisher = services.GetRequiredService(); // Load the scheduled job, and mark its task as started. - Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) return; Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); @@ -383,8 +383,8 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS // A one time execution returns the scheduled job to its active state when its execution cycle is still running, so the // running cycle keeps scheduling executions and the job can still be stopped; the same applies to a once at startup job, // whose active state is what makes it fire again at the next application startup. - bool completesTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup; - Result completeExecutionResult = scheduledJob.MarkExecutionCompleted(completesTheCycleRun); + bool doesCompleteTheCycleRun = isCycleRun || _runtimeRegistry.HasActiveCycle(scheduledJob.Id) || scheduledJob.Schedule.ScheduleType == ScheduleType.OnceAtStartup; + Result completeExecutionResult = scheduledJob.MarkExecutionCompleted(doesCompleteTheCycleRun); if (completeExecutionResult.IsFailure) return; foreach (IDomainEvent domainEvent in scheduledJob.GetDomainEvents()) @@ -412,7 +412,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS { await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); - Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) return ScheduledJobStatus.Added; ScheduledJobEntity scheduledJob = getScheduledJobResult.Value; @@ -433,17 +433,19 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS ScheduledJobStatus reconciledStatus = (openExecution?.WasCycleActive ?? true) ? ScheduledJobStatus.Active : ScheduledJobStatus.Added; Result updateScheduledJobResult = await unitOfWork.ScheduledJobRepository.UpdateAsync( - CreateUpdatedScheduledJob(scheduledJob, reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + scheduledJob.ToUpdatedRepositoryEntity(reconciledStatus, scheduledJob.LastStartedOnUtc, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); if (updateScheduledJobResult.IsFailure) return ScheduledJobStatus.Added; if (openExecution is not null) { Result updateExecutionResult = await unitOfWork.ScheduledJobExecutionRepository.UpdateAsync( - CreateClosedExecution(openExecution, DateTime.UtcNow), cancellationToken).ConfigureAwait(false); + openExecution.ToUpdatedRepositoryEntity(DateTime.UtcNow), cancellationToken).ConfigureAwait(false); if (updateExecutionResult.IsFailure) return ScheduledJobStatus.Added; } - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); _logger.LogInformation("The interrupted execution of the scheduled job '{ScheduledJobName}' was closed.", scheduledJob.Name); return reconciledStatus; } @@ -468,7 +470,7 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS { await using AsyncServiceScope scope = _serviceScopeFactory.CreateAsyncScope(); IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService(); - Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken).ConfigureAwait(false); + Result getScheduledJobResult = await unitOfWork.ScheduledJobRepository.GetByIdAsync(scheduledJobId.Value, cancellationToken: cancellationToken).ConfigureAwait(false); if (getScheduledJobResult.IsFailure || getScheduledJobResult.Value is null) return null; Result scheduledJobDomainResult = getScheduledJobResult.Value.ToDomainEntity(); @@ -488,57 +490,4 @@ public sealed class ScheduledJobSchedulerJob : BackgroundService, IScheduledJobS return schedule.GetDelayUntilNextExecution(dateTimeProvider.UtcNow, TimeZoneInfo.Local); } - /// - /// Creates a copy of with the provided status and timestamps. - /// - /// The scheduled job to copy. - /// The status of the copy. - /// The last start time of the copy. - /// The last completion time of the copy. - /// The copy of the scheduled job. - private static ScheduledJobEntity CreateUpdatedScheduledJob(ScheduledJobEntity scheduledJob, ScheduledJobStatus status, DateTime? lastStartedOnUtc, DateTime? lastCompletedOnUtc) - { - return new ScheduledJobEntity - { - Id = scheduledJob.Id, - Name = scheduledJob.Name, - TaskType = scheduledJob.TaskType, - ScheduleType = scheduledJob.ScheduleType, - IntervalMinutes = scheduledJob.IntervalMinutes, - Hour = scheduledJob.Hour, - Minute = scheduledJob.Minute, - Status = status, - OwnerUserId = scheduledJob.OwnerUserId, - LastStartedOnUtc = lastStartedOnUtc, - LastCompletedOnUtc = lastCompletedOnUtc, - CreatedOnUtc = scheduledJob.CreatedOnUtc, - CreatedBy = scheduledJob.CreatedBy, - UpdatedOnUtc = scheduledJob.UpdatedOnUtc, - UpdatedBy = scheduledJob.UpdatedBy - }; - } - - /// - /// Creates a copy of with the provided completion time. - /// - /// The execution to copy. - /// The completion time of the copy. - /// The copy of the execution. - private static ScheduledJobExecutionEntity CreateClosedExecution(ScheduledJobExecutionEntity execution, DateTime? completedOnUtc) - { - return new ScheduledJobExecutionEntity - { - Id = execution.Id, - ScheduledJobId = execution.ScheduledJobId, - TaskType = execution.TaskType, - IsCycleRun = execution.IsCycleRun, - WasCycleActive = execution.WasCycleActive, - StartedOnUtc = execution.StartedOnUtc, - CompletedOnUtc = completedOnUtc, - CreatedOnUtc = execution.CreatedOnUtc, - CreatedBy = execution.CreatedBy, - UpdatedOnUtc = execution.UpdatedOnUtc, - UpdatedBy = execution.UpdatedBy - }; - } } diff --git a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs index ed8bfaaf..5af50bcb 100644 --- a/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs +++ b/src/Lumina.Infrastructure/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutor.cs @@ -98,7 +98,9 @@ public class MediaLibraryScanTaskExecutor : IScheduledTaskExecutor domainEvents.AddRange(libraryScanResult.Value.GetDomainEvents()); } - await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); // Publish the domain events of the queued media library scans. foreach (IDomainEvent domainEvent in domainEvents) diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index b26fe59c..27d82266 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -480,7 +480,7 @@ public sealed class ThemeService : IThemeService if (unixFileType == 0xA000) return PackageInvalid("Symbolic links are not allowed in theme archives."); - Result normalizedPathResult = NormalizeRelativePath(entry.FullName, allowTrailingSlash: true); + Result normalizedPathResult = NormalizeRelativePath(entry.FullName, shouldAllowTrailingSlash: true); if (normalizedPathResult.IsFailure) return normalizedPathResult.Errors; @@ -732,14 +732,14 @@ public sealed class ThemeService : IThemeService /// Normalizes a package-relative path, rejecting paths that escape the package or violate the path rules. /// /// The package-relative path to normalize. - /// Whether a trailing slash, used for directory entries, is permitted. + /// Whether a trailing slash, used for directory entries, is permitted. /// An containing either the normalized path, or an error. - private Result NormalizeRelativePath(string path, bool allowTrailingSlash = false) + private Result NormalizeRelativePath(string path, bool shouldAllowTrailingSlash = false) { if (string.IsNullOrWhiteSpace(path) || path.Length > 240 || path.Contains('\\') || path.Contains('\0') || path.StartsWith('/') || path.Contains("//")) return PackageInvalid("The theme contains an invalid path."); - string candidate = allowTrailingSlash ? path.TrimEnd('/') : path; + string candidate = shouldAllowTrailingSlash ? path.TrimEnd('/') : path; if (string.IsNullOrWhiteSpace(candidate)) return PackageInvalid("The theme contains an invalid path."); diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs index 7a0e94b4..278e3175 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeSynchronizer.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.UoW; +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.Domain.Common.Primitives; @@ -30,7 +32,7 @@ internal static class ThemeSynchronizer /// Cancellation token that can be used to stop the execution. internal static async Task SynchronizeAsync(IThemeService themeService, IUnitOfWork unitOfWork, ILogger logger, CancellationToken cancellationToken) { - Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + Result> getThemesResult = await unitOfWork.ThemeRepository.GetAllAsync(cancellationToken: cancellationToken).ConfigureAwait(false); if (getThemesResult.IsFailure) { logger.LogWarning("Failed to read the installed themes: {Error}", getThemesResult.FirstError.Description); @@ -38,7 +40,7 @@ internal static class ThemeSynchronizer } // Themes that were soft deleted by the user must not be reinstalled automatically. - List themes = [.. getThemesResult.Value]; + List themes = [.. getThemesResult.Value.Data]; foreach (string archivePath in themeService.GetBundledThemeArchivePaths()) { @@ -107,7 +109,9 @@ internal static class ThemeSynchronizer await CleanUpMissingThemePacksAsync(themeService, unitOfWork, themes, logger, cancellationToken).ConfigureAwait(false); await EnsureCurrentThemeExistsAsync(themeService, unitOfWork, themes, cancellationToken).ConfigureAwait(false); - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + Result saveChangesResult = await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + throw new InvalidOperationException(saveChangesResult.FirstError.Description); } /// diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs new file mode 100644 index 00000000..dd1fafd4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs @@ -0,0 +1,22 @@ +namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Albums route. + /// + public static class Albums + { + public const string GET_ARTIST_ALBUMS = "/libraries/{libraryId}/artists/{artistId}/albums"; + public const string GET_ARTIST_ALBUMS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/lite"; + public const string ADD_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums"; + public const string GET_ALBUM_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + public const string UPDATE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + public const string DELETE_ALBUM = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"; + public const string GET_ALBUM_TRACKS = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; + public const string GET_ALBUM_TRACKS_LITE = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs new file mode 100644 index 00000000..b3d50a4a --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs @@ -0,0 +1,20 @@ +namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Artists route. + /// + public static class Artists + { + public const string GET_ARTIST_BY_ID = "/libraries/{libraryId}/artists/{artistId}"; + public const string GET_ARTISTS = "/libraries/{libraryId}/artists"; + public const string GET_ARTISTS_LITE = "/libraries/{libraryId}/artists/lite"; + public const string ADD_ARTIST = "/libraries/{libraryId}/artists"; + public const string UPDATE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; + public const string DELETE_ARTIST = "/libraries/{libraryId}/artists/{artistId}"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs new file mode 100644 index 00000000..b17a5043 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -0,0 +1,18 @@ +namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; + +/// +/// Class for the collection of routes defined in this API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the Tracks route. + /// + public static class Tracks + { + public const string ADD_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; + public const string GET_TRACK_BY_ID = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; + } +} diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs index 49959c37..9d231f16 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs @@ -10,15 +10,15 @@ public static partial class ApiRoutes /// public static class Books { - public const string GET_BOOK_BY_ID = "/books/{id}"; - public const string GET_BOOKS = "/books"; - public const string GET_BOOKS_LITE = "/books/lite"; - public const string ADD_BOOK = "/books"; - public const string UPDATE_BOOK = "/books/{id}"; - public const string UPDATE_BOOK_COVER = "/books/{id}/cover"; - public const string GET_BOOK_READING_MANIFEST = "/books/{bookId}/reading/manifest"; - public const string GET_BOOK_READING_AVAILABILITY = "/books/{bookId}/reading/availability"; - public const string GET_BOOK_READING_SECTION = "/books/{bookId}/reading/sections/{locationRef}"; - public const string GET_BOOK_READING_RESOURCE = "/books/{bookId}/reading/resources/{resourceKey}"; + public const string GET_BOOK_BY_ID = "/libraries/{libraryId}/books/{bookId}"; + public const string GET_BOOKS = "/libraries/{libraryId}/books"; + public const string GET_BOOKS_LITE = "/libraries/{libraryId}/books/lite"; + public const string ADD_BOOK = "/libraries/{libraryId}/books"; + public const string UPDATE_BOOK = "/libraries/{libraryId}/books/{bookId}"; + public const string UPDATE_BOOK_COVER = "/libraries/{libraryId}/books/{bookId}/cover"; + public const string GET_BOOK_READING_MANIFEST = "/libraries/{libraryId}/books/{bookId}/reading/manifest"; + public const string GET_BOOK_READING_AVAILABILITY = "/libraries/{libraryId}/books/{bookId}/reading/availability"; + public const string GET_BOOK_READING_SECTION = "/libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef}"; + public const string GET_BOOK_READING_RESOURCE = "/libraries/{libraryId}/books/{bookId}/reading/resources/{resourceKey}"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs index 373f0ad2..e0eaa893 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Permissions/GetPermissions/GetPermissionsEndpointSummary.cs @@ -39,7 +39,7 @@ public class GetPermissionsEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", + detail = "Authentication failed", instance = "/api/v1/auth/roles" }, new @@ -62,7 +62,7 @@ public class AddRoleEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + detail = "The token has expired", instance = "/api/v1/auth/roles" }, new diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs index e3a6dc87..dee79d86 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpoint.cs @@ -14,7 +14,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; /// -/// API endpoint for the /auth/roles route. +/// API endpoint for the /auth/roles/{roleId} route. /// public class DeleteRoleEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs index cab80097..aa16544a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointSummary.cs @@ -40,7 +40,7 @@ public class DeleteRoleEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", + detail = "Authentication failed", instance = "/api/v1/auth/roles" }, new @@ -42,7 +42,7 @@ public class GetRolesEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + detail = "The token has expired", instance = "/api/v1/auth/roles" }, new diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs index d0c9117c..bc181527 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointSummary.cs @@ -56,7 +56,7 @@ public class UpdateRoleEndpointSummary : Summary r.Path, "The file system path for which to get the directories. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); Response(200, "The list of directories for the specified path is returned.", example: new DirectoryResponse[] { @@ -49,7 +49,7 @@ public class GetDirectoriesEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", + detail = "Authentication failed", instance = "/api/v1/drives/get-drives" }, new @@ -44,7 +44,7 @@ public class GetDrivesEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + detail = "The token has expired", instance = "/api/v1/drives/get-drives" }, new diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs index 9ca34185..f6010ea9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointSummary.cs @@ -34,7 +34,7 @@ public class GetTypeEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", + detail = "Authentication failed", instance = "/api/v1/file-system/get-type" }, new @@ -42,7 +42,7 @@ public class GetTypeEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + detail = "The token has expired", instance = "/api/v1/file-system/get-type" }, new diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs index 690e8ac2..0616d7dc 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -26,15 +26,15 @@ public class GetFilesEndpointSummary : Summary r.Path, "The file system path for which to get the files. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); Response(200, "The list of files is returned.", example: new FileResponse[] { @@ -50,7 +50,7 @@ public class GetFilesEndpointSummary : Summary r.Path, "The file system path for which to get the tree files. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); Response(200, "The tree structure of files is returned.", example: new FileSystemTreeNodeResponse[] { @@ -50,7 +50,7 @@ public class GetTreeFilesEndpointSummary : Summary r.Path, "The file system path to check the exitence of. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden elements in the search results, or not. Optional."); Response(200, "Indicates whether the file system path exists.", example: new PathExistsResponse( @@ -48,7 +48,7 @@ public class CheckPathExistsEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums route. +/// +public class AddAlbumEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addAlbumCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add album commands. + public AddAlbumEndpoint(ICommandHandler> addAlbumCommandHandler) + { + _addAlbumCommandHandler = addAlbumCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Albums.ADD_ALBUM); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds an album stored in . + /// + /// The request containing the album to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddAlbumRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + Result result = await _addAlbumCommandHandler.HandleAsync(request.ToCommand(libraryId, artistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1/libraries/{libraryId}/artists/{artistId}/albums/{result.Value.Id}", result.Value), Problem); + } +} 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 new file mode 100644 index 00000000..a039dd41 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs @@ -0,0 +1,781 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddAlbumEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddAlbumEndpointSummary() + { + Summary = "Adds a new album to an artist."; + Description = "Creates a new album and returns its details, including the location of the newly created resource. The request is handled by an Admin, who can add albums to all libraries, or by the owner of the library."; + + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + + ExampleRequest = new AddAlbumRequest( + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12, + 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") + ] + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: + [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: + [ + new( + 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.", + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980, + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + 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: "epic") + ] + ), + TrackNumber: 1, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.CMajor, + Bpm: 72, + Work: "Bohemian Rhapsody", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Moods: + [ + new(Name: "dramatic"), + new(Name: "anxious") + ], + Isrcs: + [ + new(Value: "GBUM71029604") + ] + ), + new( + Path: "/music/queen/a-night-at-the-opera/02-youre-my-best-friend.flac", + Metadata: new( + Title: "You're My Best Friend", + OriginalTitle: "You're My Best Friend", + Description: "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + DurationInSeconds: 181, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912, + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1976, 6, 18), + OriginalReleaseYear: 1976, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: + [ + new(Name: "Rock"), + new(Name: "Pop Rock") + ], + Tags: + [ + new(Name: "classic"), + new(Name: "love") + ] + ), + TrackNumber: 7, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.BMajor, + Bpm: 118, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.BassGuitar + ) + ], + Ratings: + [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Moods: + [ + new(Name: "happy"), + new(Name: "romantic") + ], + Isrcs: + [ + new(Value: "GBUM71029605") + ] + ) + ] + ); + + RequestParam(r => r.Metadata, "The album metadata of the album. Required."); + RequestParam(r => r.Metadata!.Title, "The title of the album. Required."); + RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the album. Optional."); + RequestParam(r => r.Metadata!.Description, "The description of the album. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album. Optional."); + RequestParam(r => 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!.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."); + RequestParam(r => r.Metadata!.Language, "The language of the album. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album. Required."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English. Required."); + RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the album, if it has been translated. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album. Optional."); + RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album. Required."); + RequestParam(r => 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.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."); + RequestParam(r => r.Contributors, "The list of media contributors that performed on the album. Required."); + RequestParam(r => r.Ratings, "The list of ratings for this album. Required."); + RequestParam(r => r.Tracks, "The list of tracks of the album. Required."); + + ResponseParam(r => r.Id, "The Id of the album."); + ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); + 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!.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.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."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the album was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the album was last updated, if applicable."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this album."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the album."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); + ResponseParam(r => r.Tracks, "The list of tracks of the album."); + + Response(201, "The newly created album is returned.", + example: new AlbumResponse( + Id: albumId, + ArtistId: artistId, + LibraryId: libraryId, + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + 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") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default, + Contributors: [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: + [ + new( + Id: Guid.NewGuid(), + AlbumId: albumId, + LibraryId: libraryId, + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + 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 + ), + 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: default, + Contributors: [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Moods: [ + new(Name: "dramatic"), + new(Name: "anxious") + ], + Isrcs: [ + new(Value: "GBUM71029604") + ] + ), + new( + Id: Guid.NewGuid(), + AlbumId: albumId, + LibraryId: libraryId, + Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Metadata: new( + Title: "You're My Best Friend", + OriginalTitle: "You're My Best Friend", + Description: "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1976, 6, 18), + OriginalReleaseYear: 1976, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new(Name: "classic"), + new(Name: "love") + ], + Genres: [ + new(Name: "Rock"), + new(Name: "Pop Rock") + ], + DurationInSeconds: 181, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912 + ), + TrackNumber: 7, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.BMajor, + Bpm: 118, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default, + Contributors: [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new( + Value: 4.2M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 1234 + ), + new( + Value: 4.4M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 567 + ) + ], + Moods: [ + new(Name: "happy"), + new(Name: "warm") + ], + Isrcs: [ + new(Value: "GBUM71029609") + ] + ) + ] + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist, its media library, or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because an album with the same identity already exists, or because a unique constraint was violated.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "AlbumAlreadyExists", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "MetadataCannotBeNull", + "AlbumTitleCannotBeEmpty", + "AlbumTitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "UnknownMusicReleaseType", + "UnknownMusicReleaseStatus", + "TotalDiscsMustBeGreaterThanZero", + "TotalTracksMustBeGreaterThanZero", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "UnknownMusicMediaFormat", + "CatalogNumberMustBeMaximum50CharactersLong", + "BarcodeValueCannotBeEmpty", + "InvalidFormatForBarcode", + "MusicBrainzIdInvalidFormat", + "ContributorsListCannotBeNull", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TracksListCannotBeNull", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "TitleCannotBeEmpty", + "TitleMustBeMaximum255CharactersLong", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "TrackPathMustBeWithinLibraryContentLocations" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpoint.cs new file mode 100644 index 00000000..6f5078bb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId} route. +/// +public class DeleteAlbumEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteAlbumCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete album commands. + public DeleteAlbumEndpoint(ICommandHandler> deleteAlbumCommandHandler) + { + _deleteAlbumCommandHandler = deleteAlbumCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Albums.DELETE_ALBUM); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes an album by Id. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + Result result = await _deleteAlbumCommandHandler + .HandleAsync(new DeleteAlbumCommand(libraryId, artistId, albumId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs new file mode 100644 index 00000000..1a3b17eb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteAlbumEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteAlbumEndpointSummary() + { + Summary = "Deletes an existing album."; + Description = "Deletes the album identified by the route, together with its tracks. An artist must always keep at least one album. The album is deleted by an Admin, who can delete the albums of all libraries, or by the owner of the library of the album."; + + Response(200, "The album was successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin or the owner of the media library, or because deleting the album would leave its artist without any albums.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ArtistMustHaveAtLeastOneAlbum", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the requested artist, album, or their media library does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs new file mode 100644 index 00000000..99b843b7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId} route. +/// +public class GetAlbumEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getAlbumQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get album queries. + public GetAlbumEndpoint(IQueryHandler> getAlbumQueryHandler) + { + _getAlbumQueryHandler = getAlbumQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Albums.GET_ALBUM_BY_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets an album by Id. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + GetAlbumQuery query = new(libraryId, artistId, albumId); + Result result = await _getAlbumQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointSummary.cs new file mode 100644 index 00000000..8c2d8c66 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointSummary.cs @@ -0,0 +1,221 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetAlbumEndpointSummary() + { + Summary = "Gets an album by its Id."; + Description = "Returns the full details of the album identified by the route. The album is returned to an Admin, who can see the albums of all libraries, or to the owner of the library of the album."; + + ResponseParam(r => r.Id, "The Id of the album."); + ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); + 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!.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.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."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the album was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the album was last updated, if applicable."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this album."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the album."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); + ResponseParam(r => r.Tracks, "The list of tracks of the album."); + + Response(200, "The requested album is returned.", + example: new AlbumResponse( + Id: Guid.NewGuid(), + ArtistId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Metadata: new AlbumMetadataDto( + 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.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "vinyl") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: [] + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested album does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs new file mode 100644 index 00000000..11ce25b1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks route. +/// +public class GetAlbumTracksEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getAlbumTracksQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get album tracks queries. + public GetAlbumTracksEndpoint(IQueryHandler>> getAlbumTracksQueryHandler) + { + _getAlbumTracksQueryHandler = getAlbumTracksQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Albums.GET_ALBUM_TRACKS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of all the tracks of the album identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + GetAlbumTracksQuery query = new(libraryId, artistId, albumId); + Result> result = await _getAlbumTracksQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} 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 new file mode 100644 index 00000000..269da0ab --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs @@ -0,0 +1,328 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksEndpointSummary() + { + Summary = "Retrieves the list of tracks of an album."; + Description = "Returns the full details of the tracks of the album identified by the route. The list is returned to an Admin, who can see the tracks of the albums of all libraries, or to the owner of the library of the album."; + + ResponseParam(r => r.Id, "The Id of the track."); + ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); + ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Metadata!.Title, "The title of the track."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); + ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); + ResponseParam(r => r.TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable."); + 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.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.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."); + ResponseParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the track, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this track."); + ResponseParam(r => r.Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds."); + ResponseParam(r => r.Metadata!.SampleRate, "The sample rate of the audio of the track in Hz."); + ResponseParam(r => r.Metadata!.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.Metadata!.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.Metadata!.AudioCodec, "The audio codec used by the track, if applicable."); + ResponseParam(r => r.Metadata!.Bitrate, "The bitrate of the audio of the track in kbps, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the track."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track."); + + Response(200, "The list of tracks of the album is returned.", + example: new TrackResponse[] + { + new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980 + ), + 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, + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Moods: [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029604") + ] + ), + new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/02-youre-my-best-friend.flac", + Metadata: new AudioMetadataDto( + 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 released as the second single from the album A Night at the Opera in 1975.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "love") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Pop Rock") + ], + DurationInSeconds: 174, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912 + ), + TrackNumber: 2, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.CMajor, + Bpm: 110, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Moods: [ + new MoodDto(Name: "happy"), + new MoodDto(Name: "romantic") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029605") + ] + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested album does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpoint.cs new file mode 100644 index 00000000..0a250e2d --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite route. +/// +public class GetAlbumTracksLiteEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getAlbumTracksLiteQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get album tracks lite queries. + public GetAlbumTracksLiteEndpoint(IQueryHandler>> getAlbumTracksLiteQueryHandler) + { + _getAlbumTracksLiteQueryHandler = getAlbumTracksLiteQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Albums.GET_ALBUM_TRACKS_LITE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the lightweight read models of all the tracks of the album identified by the route. + /// + /// The request containing the pagination options of the tracks to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetAlbumTracksLiteRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + Result> result = await _getAlbumTracksLiteQueryHandler.HandleAsync(request.ToQuery(libraryId, artistId, albumId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointSummary.cs new file mode 100644 index 00000000..9d152542 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointSummary.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksLiteEndpointSummary() + { + Summary = "Retrieves the lightweight read models of the tracks of an album."; + Description = "Returns the lightweight read models of the tracks of the album identified by its Id, projecting only the fields needed to display the songs of an album, without loading the full track entities and their related data. The page is returned to an Admin, who can see the tracks of the albums of all libraries, or to the owner of the library of the album."; + + ExampleRequest = new GetAlbumTracksLiteRequest( + CurrentPage: 1, + PerPage: 48 + ); + + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of tracks to retrieve per page. Optional."); + + ResponseParam(r => r.Id, "The Id of the track."); + ResponseParam(r => r.Title, "The title of the track."); + ResponseParam(r => r.TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable."); + + Response(200, "The paginated list of the lightweight read models of the tracks of the album is returned.", + example: new PaginatedResponse + { + Data = + [ + new TrackLiteResponse( + Id: Guid.NewGuid(), + Title: "Bohemian Rhapsody", + TrackNumber: 1, + DiscNumber: 1 + ), + new TrackLiteResponse( + Id: Guid.NewGuid(), + Title: "You're My Best Friend", + TrackNumber: 2, + DiscNumber: 1 + ) + ], + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested album does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpoint.cs new file mode 100644 index 00000000..91684e6b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId} route. +/// +public class UpdateAlbumEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateAlbumCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update album commands. + public UpdateAlbumEndpoint(ICommandHandler> updateAlbumCommandHandler) + { + _updateAlbumCommandHandler = updateAlbumCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Albums.UPDATE_ALBUM); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates an album stored in . + /// + /// The request containing the album to be updated. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateAlbumRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + Result result = await _updateAlbumCommandHandler.HandleAsync(request.ToCommand(libraryId, artistId, albumId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointSummary.cs new file mode 100644 index 00000000..3adee0c2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointSummary.cs @@ -0,0 +1,411 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumEndpointSummary() + { + Summary = "Updates an existing album."; + Description = "Updates the details of the album identified by the route, returning the full details of the updated album. The album is updated by an Admin, who can update the albums of all libraries, or by the owner of the library of the album."; + + RequestParam(r => r.Metadata, "The album metadata of the album. Required."); + RequestParam(r => r.Metadata!.Title, "The title of the album. Required."); + RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the album. Optional."); + RequestParam(r => r.Metadata!.Description, "The description of the album. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album. Optional."); + RequestParam(r => 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!.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."); + RequestParam(r => r.Metadata!.Language, "The language of the album. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album. Required."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English. Required."); + RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the album, if it has been translated. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album. Optional."); + RequestParam(r => r.Metadata!.Genres, "The list of genres associated with the album. Required."); + RequestParam(r => 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.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."); + RequestParam(r => r.Contributors, "The list of media contributors that performed on the album. Required."); + RequestParam(r => r.Ratings, "The list of ratings for this album. Required."); + + ExampleRequest = new UpdateAlbumRequest( + Metadata: new AlbumMetadataDto( + 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.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12, + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: + [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: + [ + new TagDto(Name: "classic"), + new TagDto(Name: "vinyl") + ] + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: + [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ); + + ResponseParam(r => r.Id, "The Id of the album."); + ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); + 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!.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.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."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the album was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the album was last updated, if applicable."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this album."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the album."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); + ResponseParam(r => r.Tracks, "The list of tracks of the album."); + + Response(200, "The updated album is returned.", + example: new AlbumResponse( + Id: Guid.NewGuid(), + ArtistId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Metadata: new AlbumMetadataDto( + 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.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "vinyl") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: [] + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist or album, its media library, or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because a unique constraint was violated.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "MetadataCannotBeNull", + "AlbumTitleCannotBeEmpty", + "AlbumTitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "UnknownMusicReleaseType", + "UnknownMusicReleaseStatus", + "TotalDiscsMustBeGreaterThanZero", + "TotalTracksMustBeGreaterThanZero", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "UnknownMusicMediaFormat", + "CatalogNumberMustBeMaximum50CharactersLong", + "BarcodeValueCannotBeEmpty", + "InvalidFormatForBarcode", + "MusicBrainzIdInvalidFormat", + "ContributorsListCannotBeNull", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpoint.cs new file mode 100644 index 00000000..f09c0ff7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; + +/// +/// API endpoint for the /libraries/{libraryId}/artists route. +/// +public class AddArtistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addArtistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add artist commands. + public AddArtistEndpoint(ICommandHandler> addArtistCommandHandler) + { + _addArtistCommandHandler = addArtistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Artists.ADD_ARTIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds an artist stored in . + /// + /// The request containing the artist to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddArtistRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result result = await _addArtistCommandHandler.HandleAsync(request.ToCommand(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1/libraries/{libraryId}/artists/{result.Value.Id}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointSummary.cs new file mode 100644 index 00000000..2e2d5dbe --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointSummary.cs @@ -0,0 +1,930 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddArtistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddArtistEndpointSummary() + { + Summary = "Adds a new artist."; + Description = "Creates a new artist and returns its details, including the location of the newly created resource. The request is handled by an Admin, who can add artists to all libraries, or by the owner of the library."; + + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + + ExampleRequest = new AddArtistRequest( + Name: "Queen", + Website: "https://www.queenonline.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Albums: [ + new( + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new(Name: "classic"), + new(Name: "vinyl") + ], + Genres: [ + new(Name: "Rock"), + new(Name: "Progressive Rock") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: [ + new( + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + 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 + ), + TrackNumber: 1, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.CMajor, + Bpm: 72, + Work: "Bohemian Rhapsody", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Moods: [ + new(Name: "dramatic"), + new(Name: "anxious") + ], + Isrcs: [ + new(Value: "GBUM71029604") + ], + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ), + new( + Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Metadata: new( + Title: "You're My Best Friend", + OriginalTitle: "You're My Best Friend", + Description: "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1976, 6, 18), + OriginalReleaseYear: 1976, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new(Name: "classic"), + new(Name: "love") + ], + Genres: [ + new(Name: "Rock"), + new(Name: "Pop Rock") + ], + DurationInSeconds: 181, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912 + ), + TrackNumber: 7, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.BMajor, + Bpm: 118, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Moods: [ + new(Name: "happy"), + new(Name: "warm") + ], + Isrcs: [ + new(Value: "GBUM71029609") + ], + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.BassGuitar + ) + ], + Ratings: [ + new( + Value: 4.2M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 1234 + ), + new( + Value: 4.4M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 567 + ) + ] + ) + ] + ) + ] + ); + + RequestParam(r => r.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."); + RequestParam(r => r.Albums, "The list of albums of the artist, each with its own list of tracks. Required."); + RequestParam(r => r.Albums![0].Metadata, "The album metadata of the album. Required."); + RequestParam(r => r.Albums![0].Metadata!.Title, "The title of the album. Required."); + RequestParam(r => r.Albums![0].Metadata!.OriginalTitle, "The original title of the album, if different from the current title. Optional."); + RequestParam(r => r.Albums![0].Metadata!.Description, "A brief description or summary of the album. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the content was released. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the content's release. Optional."); + RequestParam(r => 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!.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!.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!.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].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."); + RequestParam(r => r.Albums![0].Contributors, "The list of media contributors that performed on the album. Required."); + RequestParam(r => r.Albums![0].Ratings, "The list of ratings for this album. Required."); + RequestParam(r => r.Albums![0].Tracks, "The list of tracks of the album. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Path, "The file system path of the track. It must be inside one of the content locations of the media library that owns it. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata, "The audio metadata of the track. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Title, "The title of the track. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalTitle, "The original title of the track, if different from the current title. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Description, "A brief description or summary of the track. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the content was released. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the content's release. Optional."); + RequestParam(r => 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!.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!.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."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.SampleRate, "The sample rate of the audio of the track in Hz. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Channels, "The number of audio channels of the track. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.BitDepth, "The bit depth of the audio of the track. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.AudioCodec, "The audio codec used by the track. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Bitrate, "The bitrate of the audio of the track in kbps. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].TrackNumber, "The number of the track on its disc. Required."); + RequestParam(r => r.Albums![0].Tracks![0].DiscNumber, "The number of the disc the track belongs to. Optional."); + RequestParam(r => 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].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].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."); + + 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.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."); + ResponseParam(r => r.Albums, "The list of albums of the artist, each with its own list of tracks."); + ResponseParam(r => r.Albums![0].Id, "The Id of the album."); + ResponseParam(r => r.Albums![0].ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.Albums![0].LibraryId, "The Id of the media library this album belongs to."); + ResponseParam(r => r.Albums![0].Metadata, "The album metadata of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Title, "The title of the album."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalTitle, "The original title of the album, if different from the current title."); + ResponseParam(r => r.Albums![0].Metadata!.Description, "A brief description or summary of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo, "The release information of the album, including its release date and other relevant details."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the album was released."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Language, "The language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Language!.LanguageCode, "The ISO code of the language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Language!.LanguageName, "The name of the language of the album in English."); + ResponseParam(r => r.Albums![0].Metadata!.Language!.NativeName, "The native name of the language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalLanguage, "The original language of the album, if it has been translated."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the album in English."); + ResponseParam(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!.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].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."); + ResponseParam(r => r.Albums![0].CreatedOnUtc, "The date and time when the album was created."); + ResponseParam(r => r.Albums![0].UpdatedOnUtc, "The date and time when the album was last updated, if applicable."); + ResponseParam(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); + ResponseParam(r => r.Albums![0].Ratings, "The list of ratings for the album."); + ResponseParam(r => r.Albums![0].Tracks, "The list of tracks of the album."); + ResponseParam(r => r.Albums![0].Tracks![0].Id, "The Id of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to."); + ResponseParam(r => r.Albums![0].Tracks![0].Path, "The file system path of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata, "The audio metadata of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Title, "The title of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalTitle, "The original title of the track, if different from the current title."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Description, "A brief description or summary of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo, "The release information of the track, including its release date and other relevant details."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the track was released."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language, "The language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageCode, "The ISO code of the language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageName, "The name of the language of the track in English."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.NativeName, "The native name of the language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage, "The original language of the track, if it has been translated."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the track in English."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Tags, "The list of tags of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Genres, "The list of genres of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.SampleRate, "The sample rate of the audio of the track in Hz."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.AudioCodec, "The audio codec used by the track, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Bitrate, "The bitrate of the audio of the track in kbps, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.Albums![0].Tracks![0].DiscNumber, "The number of the disc the track belongs to, if applicable."); + ResponseParam(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].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].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."); + ResponseParam(r => r.Albums![0].Tracks![0].Isrcs, "The list of ISRC (International Standard Recording Code) of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Contributors, "The list of references to the media contributors that performed on the track, each with the role they played."); + ResponseParam(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the artist was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); + + Response(201, "The new artist is returned.", + example: new ArtistResponse( + Id: artistId, + LibraryId: libraryId, + Name: "Queen", + Website: "https://www.queenonline.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: + [ + new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Vocals), + new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Guitar) + ], + Albums: + [ + new( + Id: albumId, + ArtistId: artistId, + LibraryId: libraryId, + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + 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") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default, + Contributors: [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: + [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: + [ + new( + Id: Guid.NewGuid(), + AlbumId: albumId, + LibraryId: libraryId, + 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.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + 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 + ), + 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: default, + Moods: + [ + new(Name: "dramatic"), + new(Name: "anxious") + ], + Isrcs: + [ + new(Value: "GBUM71029604") + ], + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ), + new( + Id: Guid.NewGuid(), + AlbumId: albumId, + LibraryId: libraryId, + Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Metadata: new( + Title: "You're My Best Friend", + OriginalTitle: "You're My Best Friend", + Description: "A song by the British rock band Queen, written by bass guitarist John Deacon. It was originally released on the album A Night at the Opera in 1975 and as a single in 1976.", + ReleaseInfo: new( + OriginalReleaseDate: new DateOnly(1976, 6, 18), + OriginalReleaseYear: 1976, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: + [ + new(Name: "classic"), + new(Name: "love") + ], + Genres: + [ + new(Name: "Rock"), + new(Name: "Pop Rock") + ], + DurationInSeconds: 181, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912 + ), + TrackNumber: 7, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.BMajor, + Bpm: 118, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default, + Moods: + [ + new(Name: "happy"), + new(Name: "warm") + ], + Isrcs: + [ + new(Value: "GBUM71029609") + ], + Contributors: + [ + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new( + Value: 4.2M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 1234 + ), + new( + Value: 4.4M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 567 + ) + ] + ) + ] + ) + ], + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: default + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin or the owner of the media library, or because the artist would be created without any albums.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ArtistMustHaveAtLeastOneAlbum", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the media library or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(409, "The request failed because an artist with the same identity already exists, or because a unique constraint was violated.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ArtistAlreadyExists", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistNameCannotBeEmpty", + "ArtistNameMustBeMaximum255CharactersLong", + "ArtistWebsiteMustBeMaximum2048CharactersLong", + "MusicBrainzIdInvalidFormat", + "ContributorsListCannotBeNull", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", + "AlbumsListCannotBeNull", + "MetadataCannotBeNull", + "AlbumTitleCannotBeEmpty", + "AlbumTitleMustBeMaximum255CharactersLong", + "TitleCannotBeEmpty", + "TitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "UnknownMusicReleaseType", + "UnknownMusicReleaseStatus", + "TotalDiscsMustBeGreaterThanZero", + "TotalTracksMustBeGreaterThanZero", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "UnknownMusicMediaFormat", + "CatalogNumberMustBeMaximum50CharactersLong", + "BarcodeValueCannotBeEmpty", + "InvalidFormatForBarcode", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TracksListCannotBeNull", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "TrackPathMustBeWithinLibraryContentLocations" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpoint.cs new file mode 100644 index 00000000..4ff1bf31 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpoint.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId} route. +/// +public class DeleteArtistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteArtistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete artist commands. + public DeleteArtistEndpoint(ICommandHandler> deleteArtistCommandHandler) + { + _deleteArtistCommandHandler = deleteArtistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Artists.DELETE_ARTIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes an artist by Id. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + Result result = await _deleteArtistCommandHandler.HandleAsync(new DeleteArtistCommand(libraryId, artistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs new file mode 100644 index 00000000..c9149866 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteArtistEndpointSummary() + { + Summary = "Deletes an existing artist."; + Description = "Deletes the artist identified by the route, together with its albums and tracks. The artist is deleted by an Admin, who can delete the artists of all libraries, or by the owner of the library of the artist."; + + Response(200, "The artist was successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist or its media library does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs new file mode 100644 index 00000000..bf1efd34 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId} route. +/// +public class GetArtistEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getArtistQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get artist queries. + public GetArtistEndpoint(IQueryHandler> getArtistQueryHandler) + { + _getArtistQueryHandler = getArtistQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Artists.GET_ARTIST_BY_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets an artist by Id. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + GetArtistQuery query = new(libraryId, artistId); + Result result = await _getArtistQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointSummary.cs new file mode 100644 index 00000000..299c1e09 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointSummary.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetArtistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistEndpointSummary() + { + Summary = "Gets an artist by its Id."; + Description = "Returns the full details of the artist identified by the route. The artist is returned to an Admin, who can see the artists of all libraries, or to the owner of the library of the artist."; + + 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.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."); + ResponseParam(r => r.Albums, "The list of albums of the artist, each with its own list of tracks."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the artist was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); + + Response(200, "The requested artist is returned.", + example: new ArtistResponse( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Name: "Queen", + Website: "https://www.queenonline.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: + [ + new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Vocals), + new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Guitar) + ], + Albums: [], + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs new file mode 100644 index 00000000..2df64426 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums route. +/// +public class GetArtistAlbumsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getArtistAlbumsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get artist albums queries. + public GetArtistAlbumsEndpoint(IQueryHandler>> getArtistAlbumsQueryHandler) + { + _getArtistAlbumsQueryHandler = getArtistAlbumsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Albums.GET_ARTIST_ALBUMS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of all the albums of the artist identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + GetArtistAlbumsQuery query = new(libraryId, artistId); + Result> result = await _getArtistAlbumsQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} 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 new file mode 100644 index 00000000..447e7594 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs @@ -0,0 +1,296 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsEndpointSummary() + { + Summary = "Retrieves the list of albums of an artist."; + Description = "Returns the full details of the albums of the artist identified by the route, with the full details of each album. The list is returned to an Admin, who can see the albums of the artists of all libraries, or to the owner of the library of the artist."; + + ResponseParam(r => r.Id, "The Id of the album."); + ResponseParam(r => r.ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the album belongs to."); + 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!.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.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."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the album was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the album was last updated, if applicable."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this album."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the album, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the album, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the album."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album."); + ResponseParam(r => r.Tracks, "The list of tracks of the album."); + + Response(200, "The list of albums of the artist is returned.", + example: new AlbumResponse[] + { + new AlbumResponse( + Id: Guid.NewGuid(), + ArtistId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Metadata: new AlbumMetadataDto( + 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.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "vinyl") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: [] + ), + new AlbumResponse( + Id: Guid.NewGuid(), + ArtistId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Metadata: new AlbumMetadataDto( + Title: "The Works", + OriginalTitle: "The Works", + Description: "The eleventh studio album by the British rock band Queen, released in 1984. It was the first Queen album to be released on CD.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1984, 2, 27), + OriginalReleaseYear: 1984, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Pop Rock") + ], + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "compact disc") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 9 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282771043", + CatalogNumber: "EMC 2400141", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: [] + ) + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpoint.cs new file mode 100644 index 00000000..219829e2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/lite route. +/// +public class GetArtistAlbumsLiteEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getArtistAlbumsLiteQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get artist albums lite queries. + public GetArtistAlbumsLiteEndpoint(IQueryHandler>> getArtistAlbumsLiteQueryHandler) + { + _getArtistAlbumsLiteQueryHandler = getArtistAlbumsLiteQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Albums.GET_ARTIST_ALBUMS_LITE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the lightweight read models of all the albums of the artist identified by the route. + /// + /// The request containing the pagination options of the albums to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistAlbumsLiteRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + Result> result = await _getArtistAlbumsLiteQueryHandler.HandleAsync(request.ToQuery(libraryId, artistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointSummary.cs new file mode 100644 index 00000000..c474f5c9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointSummary.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsLiteEndpointSummary() + { + Summary = "Retrieves the lightweight read models of the albums of an artist."; + Description = "Returns the lightweight read models of the albums of the artist identified by its Id, projecting only the fields needed to display the albums in a card-based grid, without loading the full album entities and their related data. The page is returned to an Admin, who can see the albums of the artists of all libraries, or to the owner of the library of the artist."; + + ExampleRequest = new GetArtistAlbumsLiteRequest( + CurrentPage: 1, + PerPage: 48 + ); + + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of albums to retrieve per page. Optional."); + + ResponseParam(r => r.Id, "The Id of the album."); + ResponseParam(r => r.Title, "The title of the album."); + ResponseParam(r => r.TotalTracks, "The number of tracks of the release."); + + Response(200, "The paginated list of the lightweight read models of the albums of the artist is returned.", + example: new PaginatedResponse + { + Data = + [ + new AlbumLiteResponse( + Id: Guid.NewGuid(), + Title: "A Night at the Opera", + TotalTracks: 12 + ), + new AlbumLiteResponse( + Id: Guid.NewGuid(), + Title: "The Works", + TotalTracks: 9 + ) + ], + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpoint.cs new file mode 100644 index 00000000..e60695a4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; + +/// +/// API endpoint for the /libraries/{libraryId}/artists route. +/// +public class GetArtistsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getArtistsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get artists queries. + public GetArtistsEndpoint(IQueryHandler>> getArtistsQueryHandler) + { + _getArtistsQueryHandler = getArtistsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Artists.GET_ARTISTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the list of all the artists of the media library identified by the route. + /// + /// The request containing the pagination and filtering options of the artists to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistsRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getArtistsQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointSummary.cs new file mode 100644 index 00000000..f154e2ab --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointSummary.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistsEndpointSummary() + { + Summary = "Retrieves the list of artists of a media library."; + Description = "Returns the paginated list of the artists of the media library identified by the route, with the full details of each artist. The page is returned to an Admin, who can see the artists of all libraries, or to the owner of the library."; + + ExampleRequest = new GetArtistsRequest( + CurrentPage: 1, + PerPage: 48, + SearchTerm: "queen" + ); + + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of artists to retrieve per page. Optional."); + RequestParam(r => r.SearchTerm, "The search term used to filter the artists by name. Optional."); + + 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.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."); + ResponseParam(r => r.Albums, "The list of albums of the artist, each with its own list of tracks."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the artist was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); + + Response(200, "The paginated list of the artists of the media library is returned.", + example: new PaginatedResponse + { + Data = + [ + new ArtistResponse( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Name: "Queen", + Website: "https://www.queenonline.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: [], + Albums: [], + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow + ), + new ArtistResponse( + Id: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Name: "David Bowie", + Website: "https://www.davidbowie.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: [], + Albums: [], + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow + ) + ], + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpoint.cs new file mode 100644 index 00000000..534c9314 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/lite route. +/// +public class GetArtistsLiteEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getArtistsLiteQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get artists lite queries. + public GetArtistsLiteEndpoint(IQueryHandler>> getArtistsLiteQueryHandler) + { + _getArtistsLiteQueryHandler = getArtistsLiteQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Artists.GET_ARTISTS_LITE); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the lightweight read models of all the artists of the media library identified by the route. + /// + /// The request containing the pagination and filtering options of the artists to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistsLiteRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getArtistsLiteQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointSummary.cs new file mode 100644 index 00000000..4d61839c --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointSummary.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetArtistsLiteEndpointSummary() + { + Summary = "Retrieves the lightweight read models of the artists of a media library."; + Description = "Returns the lightweight read models of the artists of a media library, projecting only the fields needed to display the artists in a card-based grid, without loading the full artist entities and their related data. The page is returned to an Admin, who can see the artists of all libraries, or to the owner of the library."; + + ExampleRequest = new GetArtistsLiteRequest( + CurrentPage: 1, + PerPage: 48, + SearchTerm: "queen" + ); + + RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); + RequestParam(r => r.PerPage, "The maximum number of artists to retrieve per page. Optional."); + RequestParam(r => r.SearchTerm, "The search term used to filter the artists by name. Optional."); + + ResponseParam(r => r.Id, "The Id of the artist."); + ResponseParam(r => r.Name, "The name of the artist."); + + Response(200, "The paginated list of the lightweight read models of the artists is returned.", + example: new PaginatedResponse + { + Data = + [ + new ArtistLiteResponse( + Id: Guid.NewGuid(), + Name: "Queen" + ), + new ArtistLiteResponse( + Id: Guid.NewGuid(), + Name: "David Bowie" + ) + ], + CurrentPage = 1, + PerPage = 10, + Count = 2, + NumberOfPages = 1 + } + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpoint.cs new file mode 100644 index 00000000..d094b125 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId} route. +/// +public class UpdateArtistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateArtistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update artist commands. + public UpdateArtistEndpoint(ICommandHandler> updateArtistCommandHandler) + { + _updateArtistCommandHandler = updateArtistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Artists.UPDATE_ARTIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the artist described in . + /// + /// The request containing the edited details of the artist. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateArtistRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + Result result = await _updateArtistCommandHandler.HandleAsync(request.ToCommand(libraryId, artistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointSummary.cs new file mode 100644 index 00000000..882660ac --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointSummary.cs @@ -0,0 +1,934 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistEndpointSummary() + { + Summary = "Updates an existing artist."; + Description = "Updates the details of the artist identified by the route, together with its contributors and albums, returning the full details of the updated artist. The artist is updated by an Admin, who can update the artists of all libraries, or by the owner of the library of the artist."; + + RequestParam(r => r.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."); + RequestParam(r => r.Albums, "The list of albums of the artist, each with its own list of tracks. Required."); + RequestParam(r => r.Albums![0].AlbumId, "The Id of the album, when the album already exists. Optional."); + RequestParam(r => r.Albums![0].Metadata, "The album metadata of the album. Required."); + RequestParam(r => r.Albums![0].Metadata!.Title, "The title of the album. Required."); + RequestParam(r => r.Albums![0].Metadata!.OriginalTitle, "The original title of the album, if different from the current title. Optional."); + RequestParam(r => r.Albums![0].Metadata!.Description, "A brief description or summary of the album. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the content. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the content was released. Optional."); + RequestParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the content's release. Optional."); + RequestParam(r => 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!.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!.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!.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].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."); + RequestParam(r => r.Albums![0].Contributors, "The list of media contributors that performed on the album. Required."); + RequestParam(r => r.Albums![0].Ratings, "The list of ratings for this album. Required."); + RequestParam(r => r.Albums![0].Tracks, "The list of tracks of the album. Required."); + RequestParam(r => r.Albums![0].Tracks![0].TrackId, "The Id of the track, when the track already exists. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Path, "The file system path of the track. It must be inside one of the content locations of the media library that owns it. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata, "The audio metadata of the track. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Title, "The title of the track. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalTitle, "The original title of the track, if different from the current title. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Description, "A brief description or summary of the track. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the content. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the content was released. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the content's release. Optional."); + RequestParam(r => 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!.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!.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."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.SampleRate, "The sample rate of the audio of the track in Hz. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Channels, "The number of audio channels of the track. Required."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.BitDepth, "The bit depth of the audio of the track. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.AudioCodec, "The audio codec used by the track. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].Metadata!.Bitrate, "The bitrate of the audio of the track in kbps. Optional."); + RequestParam(r => r.Albums![0].Tracks![0].TrackNumber, "The number of the track on its disc. Required."); + RequestParam(r => r.Albums![0].Tracks![0].DiscNumber, "The number of the disc the track belongs to. Optional."); + RequestParam(r => 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].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].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", + Website: "https://www.queenonline.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Albums: [ + new UpdateArtistAlbumRequest( + AlbumId: Guid.NewGuid(), + Metadata: new AlbumMetadataDto( + 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.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "vinyl") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: [ + new UpdateArtistTrackRequest( + TrackId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980 + ), + TrackNumber: 1, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.CMajor, + Bpm: 72, + Work: "Bohemian Rhapsody", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Moods: [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ), + new UpdateArtistTrackRequest( + TrackId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1976, 6, 18), + OriginalReleaseYear: 1976, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "love") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Pop Rock") + ], + DurationInSeconds: 181, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912 + ), + TrackNumber: 7, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.BMajor, + Bpm: 118, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Moods: [ + new MoodDto(Name: "happy"), + new MoodDto(Name: "warm") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029609") + ], + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.BassGuitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.2M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 1234 + ), + new AudioRatingDto( + Value: 4.4M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 567 + ) + ] + ) + ] + ) + ] + ); + + 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.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."); + ResponseParam(r => r.Albums, "The list of albums of the artist, each with its own list of tracks."); + ResponseParam(r => r.Albums![0].Id, "The Id of the album."); + ResponseParam(r => r.Albums![0].ArtistId, "The Id of the artist the album belongs to."); + ResponseParam(r => r.Albums![0].LibraryId, "The Id of the media library this album belongs to."); + ResponseParam(r => r.Albums![0].Metadata, "The album metadata of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Title, "The title of the album."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalTitle, "The original title of the album, if different from the current title."); + ResponseParam(r => r.Albums![0].Metadata!.Description, "A brief description or summary of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo, "The release information of the album, including its release date and other relevant details."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the album."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the album was released."); + ResponseParam(r => r.Albums![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Language, "The language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Language!.LanguageCode, "The ISO code of the language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.Language!.LanguageName, "The name of the language of the album in English."); + ResponseParam(r => r.Albums![0].Metadata!.Language!.NativeName, "The native name of the language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalLanguage, "The original language of the album, if it has been translated."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the album."); + ResponseParam(r => r.Albums![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the album in English."); + ResponseParam(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!.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].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."); + ResponseParam(r => r.Albums![0].CreatedOnUtc, "The date and time when the album was created."); + ResponseParam(r => r.Albums![0].UpdatedOnUtc, "The date and time when the album was last updated, if applicable."); + ResponseParam(r => r.Albums![0].Contributors, "The list of references to the media contributors that performed on the album, each with the role they played."); + ResponseParam(r => r.Albums![0].Ratings, "The list of ratings for the album."); + ResponseParam(r => r.Albums![0].Tracks, "The list of tracks of the album."); + ResponseParam(r => r.Albums![0].Tracks![0].Id, "The Id of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.Albums![0].Tracks![0].LibraryId, "The Id of the media library this track belongs to."); + ResponseParam(r => r.Albums![0].Tracks![0].Path, "The file system path of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata, "The audio metadata of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Title, "The title of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalTitle, "The original title of the track, if different from the current title."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Description, "A brief description or summary of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo, "The release information of the track, including its release date and other relevant details."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release date of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release year of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseCountry, "The country where the track was released."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language, "The language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageCode, "The ISO code of the language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.LanguageName, "The name of the language of the track in English."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Language!.NativeName, "The native name of the language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage, "The original language of the track, if it has been translated."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the track in English."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Tags, "The list of tags of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Genres, "The list of genres of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.SampleRate, "The sample rate of the audio of the track in Hz."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.AudioCodec, "The audio codec used by the track, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].Metadata!.Bitrate, "The bitrate of the audio of the track in kbps, if applicable."); + ResponseParam(r => r.Albums![0].Tracks![0].TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.Albums![0].Tracks![0].DiscNumber, "The number of the disc the track belongs to, if applicable."); + ResponseParam(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].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].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."); + ResponseParam(r => r.Albums![0].Tracks![0].Isrcs, "The list of ISRC (International Standard Recording Code) of the track."); + ResponseParam(r => r.Albums![0].Tracks![0].Contributors, "The list of references to the media contributors that performed on the track, each with the role they played."); + ResponseParam(r => r.Albums![0].Tracks![0].Ratings, "The list of ratings for the track."); + ResponseParam(r => r.CreatedOnUtc, "The date and time when the artist was created."); + ResponseParam(r => r.UpdatedOnUtc, "The date and time when the artist was last updated, if applicable."); + + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + + Response(200, "The updated artist is returned.", + example: new ArtistResponse( + Id: artistId, + LibraryId: libraryId, + Name: "Queen", + Website: "https://www.queenonline.com", + MusicBrainzArtistId: Guid.NewGuid(), + Contributors: + [ + new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Vocals), + new(ContributorId: Guid.NewGuid(), Role: MediaContributorRole.Guitar) + ], + Albums: + [ + new AlbumResponse( + Id: albumId, + ArtistId: artistId, + LibraryId: libraryId, + Metadata: new AlbumMetadataDto( + 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.", + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 11, 21), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Remastered" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: + [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: + [ + new TagDto(Name: "classic"), + new TagDto(Name: "vinyl") + ], + ReleaseType: MusicReleaseType.Album, + ReleaseStatus: MusicReleaseStatus.Official, + TotalDiscs: 1, + TotalTracks: 12 + ), + MediaFormat: MusicMediaFormat.CD, + Barcode: "0042282778329", + CatalogNumber: "EMC 4008", + MusicBrainzReleaseId: Guid.NewGuid(), + MusicBrainzReleaseGroupId: Guid.NewGuid(), + MusicBrainzReleaseArtistId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Producer + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Engineer + ) + ], + Ratings: + [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ], + Tracks: + [ + new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: albumId, + LibraryId: libraryId, + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: + [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ], + Genres: + [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980 + ), + 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, + Moods: + [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: + [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ), + new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: albumId, + LibraryId: libraryId, + Path: "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1976, 6, 18), + OriginalReleaseYear: 1976, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: + [ + new TagDto(Name: "classic"), + new TagDto(Name: "love") + ], + Genres: + [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Pop Rock") + ], + DurationInSeconds: 181, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 912 + ), + TrackNumber: 7, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.BMajor, + Bpm: 118, + Work: "You're My Best Friend", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow, + Moods: + [ + new MoodDto(Name: "happy"), + new MoodDto(Name: "warm") + ], + Isrcs: + [ + new IsrcDto(Value: "GBUM71029609") + ], + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new AudioRatingDto( + Value: 4.2M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 1234 + ), + new AudioRatingDto( + Value: 4.4M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 567 + ) + ] + ) + ] + ) + ], + CreatedOnUtc: DateTime.UtcNow, + UpdatedOnUtc: DateTime.UtcNow + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin or the owner of the media library, or because the update would leave the artist without any albums.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "ArtistMustHaveAtLeastOneAlbum", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(404, "The request failed because the requested artist, its media library, or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the new artist name is already used in the library, or because a unique constraint was violated.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "ArtistNameCannotBeEmpty", + "ArtistNameMustBeMaximum255CharactersLong", + "ArtistWebsiteMustBeMaximum2048CharactersLong", + "MusicBrainzIdInvalidFormat", + "ContributorsListCannotBeNull", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", + "AlbumsListCannotBeNull", + "AlbumIdCannotBeEmpty", + "MetadataCannotBeNull", + "AlbumTitleCannotBeEmpty", + "AlbumTitleMustBeMaximum255CharactersLong", + "TitleCannotBeEmpty", + "TitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "UnknownMusicReleaseType", + "UnknownMusicReleaseStatus", + "TotalDiscsMustBeGreaterThanZero", + "TotalTracksMustBeGreaterThanZero", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "UnknownMusicMediaFormat", + "CatalogNumberMustBeMaximum50CharactersLong", + "BarcodeValueCannotBeEmpty", + "InvalidFormatForBarcode", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TracksListCannotBeNull", + "TrackIdCannotBeEmpty", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "TrackPathMustBeWithinLibraryContentLocations" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpoint.cs new file mode 100644 index 00000000..cefe1abf --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.AddTrack; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks route. +/// +public class AddTrackEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addTrackCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add track commands. + public AddTrackEndpoint(ICommandHandler> addTrackCommandHandler) + { + _addTrackCommandHandler = addTrackCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Tracks.ADD_TRACK); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds a track stored in . + /// + /// The request containing the track to be added. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddTrackRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + Result result = await _addTrackCommandHandler.HandleAsync(request.ToCommand(libraryId, artistId, albumId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{result.Value.Id}", result.Value), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointSummary.cs new file mode 100644 index 00000000..4ac2fba7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointSummary.cs @@ -0,0 +1,468 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.AddTrack; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddTrackEndpointSummary() + { + Summary = "Adds a new track to an album."; + Description = "Creates a new track in the album identified by the route and returns its details, including the location of the newly created resource. The request is handled by an Admin, who can add tracks to the albums of all libraries, or by the owner of the library."; + + ExampleRequest = new AddTrackRequest( + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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, + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: + [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: + [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ] + ), + TrackNumber: 1, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.CMajor, + Bpm: 72, + Work: "Bohemian Rhapsody", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Moods: + [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: + [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ); + + RequestParam(r => r.Path, "The file system path of the track. Required."); + RequestParam(r => r.Metadata, "The audio metadata of the track. Required."); + RequestParam(r => r.Metadata!.Title, "The title of the track. Required."); + RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the track. Optional."); + RequestParam(r => r.Metadata!.Description, "The description of the track. Optional."); + RequestParam(r => r.Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds. Required."); + RequestParam(r => r.Metadata!.SampleRate, "The sample rate of the audio of the track in Hz. Required."); + RequestParam(r => r.Metadata!.Channels, "The number of audio channels of the track. Required."); + RequestParam(r => r.Metadata!.BitDepth, "The bit depth of the audio of the track. Optional."); + RequestParam(r => r.Metadata!.AudioCodec, "The audio codec used by the track. Optional."); + RequestParam(r => r.Metadata!.Bitrate, "The bitrate of the audio of the track in kbps. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track. Optional."); + RequestParam(r => r.Metadata!.Language, "The language of the track. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the track. Required."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English. Required."); + RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the track. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the track, if it has been translated. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the track. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track. Optional."); + RequestParam(r => r.Metadata!.Genres, "The list of genres associated with the track. Required."); + RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track. Required."); + RequestParam(r => r.TrackNumber, "The number of the track on its disc. Required."); + RequestParam(r => r.DiscNumber, "The number of the disc the track belongs to. Optional."); + RequestParam(r => 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.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.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."); + RequestParam(r => r.Ratings, "The list of ratings for this track. Required."); + + ResponseParam(r => r.Id, "The Id of the track."); + ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); + ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Metadata!.Title, "The title of the track."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); + ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); + ResponseParam(r => r.TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable."); + 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.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.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."); + ResponseParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the track, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this track."); + ResponseParam(r => r.Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds."); + ResponseParam(r => r.Metadata!.SampleRate, "The sample rate of the audio of the track in Hz."); + ResponseParam(r => r.Metadata!.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.Metadata!.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.Metadata!.AudioCodec, "The audio codec used by the track, if applicable."); + ResponseParam(r => r.Metadata!.Bitrate, "The bitrate of the audio of the track in kbps, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the track."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track."); + + Response(201, "The newly created track is returned.", + example: new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980 + ), + 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: default, + Moods: [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist or album, its media library, or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because a track with the same identity or file system path already exists in the library, or because a unique constraint was violated.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "TrackAlreadyExists", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "MetadataCannotBeNull", + "TitleCannotBeEmpty", + "TitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "MusicBrainzIdInvalidFormat", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "ContributorsListCannotBeNull", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TrackPathMustBeWithinLibraryContentLocations" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpoint.cs new file mode 100644 index 00000000..5322e737 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId} route. +/// +public class DeleteTrackEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deleteTrackCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete track commands. + public DeleteTrackEndpoint(ICommandHandler> deleteTrackCommandHandler) + { + _deleteTrackCommandHandler = deleteTrackCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Tracks.DELETE_TRACK); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes a track by Id. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + Result result = await _deleteTrackCommandHandler + .HandleAsync(new DeleteTrackCommand(libraryId, artistId, albumId, trackId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs new file mode 100644 index 00000000..a9668122 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeleteTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeleteTrackEndpointSummary() + { + Summary = "Deletes an existing track."; + Description = "Deletes the track identified by the route. The track is deleted by an Admin, who can delete the tracks of all libraries, or by the owner of the library of the track."; + + Response(200, "The track was successfully deleted."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist, album, track, or their media library does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs new file mode 100644 index 00000000..41af112b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId} route. +/// +public class GetTrackEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getTrackQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track queries. + public GetTrackEndpoint(IQueryHandler> getTrackQueryHandler) + { + _getTrackQueryHandler = getTrackQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.GET_TRACK_BY_ID); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets a track by Id. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + GetTrackQuery query = new(libraryId, artistId, albumId, trackId); + Result result = await _getTrackQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs new file mode 100644 index 00000000..2df68fd7 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs @@ -0,0 +1,253 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackEndpointSummary() + { + Summary = "Gets a track by its Id."; + Description = "Returns the full details of the track identified by the route. The track is returned to an Admin, who can see the tracks of all libraries, or to the owner of the library of the track."; + + ResponseParam(r => r.Id, "The Id of the track."); + ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); + ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Metadata!.Title, "The title of the track."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); + ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); + ResponseParam(r => r.TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable."); + 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.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.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."); + ResponseParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the track, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this track."); + ResponseParam(r => r.Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds."); + ResponseParam(r => r.Metadata!.SampleRate, "The sample rate of the audio of the track in Hz."); + ResponseParam(r => r.Metadata!.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.Metadata!.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.Metadata!.AudioCodec, "The audio codec used by the track, if applicable."); + ResponseParam(r => r.Metadata!.Bitrate, "The bitrate of the audio of the track in kbps, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the track."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track."); + + Response(200, "The requested track is returned.", + example: new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980 + ), + 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, + Moods: [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested album or track does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpoint.cs new file mode 100644 index 00000000..5bc92f14 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack; + +/// +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId} route. +/// +public class UpdateTrackEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updateTrackCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update track commands. + public UpdateTrackEndpoint(ICommandHandler> updateTrackCommandHandler) + { + _updateTrackCommandHandler = updateTrackCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Tracks.UPDATE_TRACK); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates a track stored in . + /// + /// The request containing the track to be updated. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdateTrackRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + Result result = await _updateTrackCommandHandler.HandleAsync(request.ToCommand(libraryId, artistId, albumId, trackId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs new file mode 100644 index 00000000..300f67a3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs @@ -0,0 +1,466 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdateTrackEndpointSummary() + { + Summary = "Updates an existing track."; + Description = "Updates the details of the track identified by the route, returning the full details of the updated track. The track is updated by an Admin, who can update the tracks of all libraries, or by the owner of the library of the track."; + + ExampleRequest = new UpdateTrackRequest( + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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, + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Genres: + [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + Tags: + [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ] + ), + TrackNumber: 1, + DiscNumber: 1, + Script: "Latn", + Key: MusicKey.CMajor, + Bpm: 72, + Work: "Bohemian Rhapsody", + MusicBrainzRecordingId: Guid.NewGuid(), + MusicBrainzTrackId: Guid.NewGuid(), + MusicBrainzWorkId: Guid.NewGuid(), + Moods: + [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: + [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: + [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: + [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ); + + RequestParam(r => r.Path, "The file system path of the track. Required."); + RequestParam(r => r.Metadata, "The audio metadata of the track. Required."); + RequestParam(r => r.Metadata!.Title, "The title of the track. Required."); + RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the track. Optional."); + RequestParam(r => r.Metadata!.Description, "The description of the track. Optional."); + RequestParam(r => r.Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds. Required."); + RequestParam(r => r.Metadata!.SampleRate, "The sample rate of the audio of the track in Hz. Required."); + RequestParam(r => r.Metadata!.Channels, "The number of audio channels of the track. Required."); + RequestParam(r => r.Metadata!.BitDepth, "The bit depth of the audio of the track. Optional."); + RequestParam(r => r.Metadata!.AudioCodec, "The audio codec used by the track. Optional."); + RequestParam(r => r.Metadata!.Bitrate, "The bitrate of the audio of the track in kbps. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo, "The release information, including release date and other relevant details. Required."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the track. Optional."); + RequestParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track. Optional."); + RequestParam(r => r.Metadata!.Language, "The language of the track. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the track. Required."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English. Required."); + RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the track. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the track, if it has been translated. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the track. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track. Optional."); + RequestParam(r => r.Metadata!.Genres, "The list of genres associated with the track. Required."); + RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track. Required."); + RequestParam(r => r.TrackNumber, "The number of the track on its disc. Required."); + RequestParam(r => r.DiscNumber, "The number of the disc the track belongs to. Optional."); + RequestParam(r => 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.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.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."); + RequestParam(r => r.Ratings, "The list of ratings for this track. Required."); + + ResponseParam(r => r.Id, "The Id of the track."); + ResponseParam(r => r.AlbumId, "The Id of the album the track belongs to."); + ResponseParam(r => r.LibraryId, "The Id of the media library the track belongs to."); + ResponseParam(r => r.Path, "The file system path of the track."); + ResponseParam(r => r.Metadata!.Title, "The title of the track."); + ResponseParam(r => r.Metadata!.OriginalTitle, "The original title of the track, if applicable."); + ResponseParam(r => r.Metadata!.Description, "The description of the track, if applicable."); + ResponseParam(r => r.TrackNumber, "The number of the track on its disc."); + ResponseParam(r => r.DiscNumber, "The number of the disc the track belongs to, if applicable."); + 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.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.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."); + ResponseParam(r => r.Isrcs, "The list of ISRC (International Standard Recording Code) of the track."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that performed on the track, each with the role they played."); + ResponseParam(r => r.Ratings, "The list of ratings for this track."); + ResponseParam(r => r.Metadata!.DurationInSeconds, "The duration of the audio of the track in seconds."); + ResponseParam(r => r.Metadata!.SampleRate, "The sample rate of the audio of the track in Hz."); + ResponseParam(r => r.Metadata!.Channels, "The number of audio channels of the track."); + ResponseParam(r => r.Metadata!.BitDepth, "The bit depth of the audio of the track, if applicable."); + ResponseParam(r => r.Metadata!.AudioCodec, "The audio codec used by the track, if applicable."); + ResponseParam(r => r.Metadata!.Bitrate, "The bitrate of the audio of the track in kbps, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseDate, "The original release date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.OriginalReleaseYear, "The original release year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseDate, "The re-release or reissue date of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReReleaseYear, "The re-release or reissue year of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseCountry, "The country or region of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.ReleaseInfo!.ReleaseVersion, "The version or edition of the release of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageCode, "The ISO 639-1 two-letter language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO 639-1 two-letter original language code of the track, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English, if applicable."); + ResponseParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the track, if applicable."); + ResponseParam(r => r.Metadata!.Genres, "The list of genres associated with the track."); + ResponseParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track."); + + Response(200, "The updated track is returned.", + example: new TrackResponse( + Id: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + LibraryId: Guid.NewGuid(), + Path: "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", + Metadata: new AudioMetadataDto( + 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: new ReleaseInfoDto( + OriginalReleaseDate: new DateOnly(1975, 10, 31), + OriginalReleaseYear: 1975, + ReReleaseDate: default, + ReReleaseYear: default, + ReleaseCountry: ReleaseCountry.GB, + ReleaseVersion: "Original" + ), + Language: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + OriginalLanguage: new LanguageInfoDto( + LanguageCode: "en", + LanguageName: "English", + NativeName: "English" + ), + Tags: [ + new TagDto(Name: "classic"), + new TagDto(Name: "epic") + ], + Genres: [ + new GenreDto(Name: "Rock"), + new GenreDto(Name: "Progressive Rock") + ], + DurationInSeconds: 354, + SampleRate: 44100, + Channels: 2, + BitDepth: 16, + AudioCodec: "FLAC", + Bitrate: 980 + ), + 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, + Moods: [ + new MoodDto(Name: "dramatic"), + new MoodDto(Name: "anxious") + ], + Isrcs: [ + new IsrcDto(Value: "GBUM71029604") + ], + Contributors: [ + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Vocals + ), + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Guitar + ) + ], + Ratings: [ + new AudioRatingDto( + Value: 4.5M, + MaxValue: 5, + Source: AudioRatingSource.MusicBrainz, + VoteCount: 2345 + ), + new AudioRatingDto( + Value: 4.8M, + MaxValue: 5, + Source: AudioRatingSource.LastFm, + VoteCount: 1234 + ) + ] + ) + ); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested artist, album, track, their media library, or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "ArtistNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "AlbumNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the new file system path already belongs to another track in the library, or because a unique constraint was violated.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "MetadataCannotBeNull", + "TitleCannotBeEmpty", + "TitleMustBeMaximum255CharactersLong", + "OriginalTitleMustBeMaximum255CharactersLong", + "DescriptionMustBeMaximum2000CharactersLong", + "ReleaseInfoCannotBeNull", + "OriginalReleaseYearMustBeBetween1And9999", + "ReReleaseYearMustBeBetween1And9999", + "ReleaseVersionMustBeMaximum50CharactersLong", + "OriginalReleaseDateAndYearMustMatch", + "ReReleaseDateAndYearMustMatch", + "ReReleaseYearCannotBeEarlierThanOriginalReleaseYear", + "ReReleaseDateCannotBeEarlierThanOriginalReleaseDate", + "GenresListCannotBeNull", + "GenreNameCannotBeEmpty", + "GenreNameMustBeMaximum50CharactersLong", + "TagsListCannotBeNull", + "TagNameCannotBeEmpty", + "TagNameMustBeMaximum50CharactersLong", + "LanguageCodeCannotBeEmpty", + "LanguageCodeMustBe2CharactersLong", + "LanguageNameCannotBeEmpty", + "LanguageNameMustBeMaximum50CharactersLong", + "LanguageNativeNameMustBeMaximum50CharactersLong", + "MusicBrainzIdInvalidFormat", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "ContributorsListCannotBeNull", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TrackPathMustBeWithinLibraryContentLocations" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs index f980f5c2..dcfa808f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpoint.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary; /// -/// API endpoint for the /library route. +/// API endpoint for the /libraries route. /// public class AddLibraryEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index a4a28680..4eda96e1 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -88,7 +88,7 @@ public class AddLibraryEndpointSummary : Summary -/// API endpoint for the //libraries/{id} route. +/// API endpoint for the /libraries/{id} route. /// public class DeleteLibraryEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs index ed3b528d..53141ef9 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs @@ -40,7 +40,7 @@ public class DeleteLibraryEndpointSummary : Summary -/// API endpoint for the /books route. +/// API endpoint for the /libraries/{libraryId}/books route. /// public class AddBookEndpoint : BaseEndpoint { @@ -48,7 +48,9 @@ public class AddBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken) { - Result result = await _addBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result result = await _addBookCommandHandler.HandleAsync(request.ToCommand(libraryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Created($"{BaseURL}api/v1/libraries/{libraryId}/books/{result.Value.Id}", result.Value), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs index 2988ff81..1ea89bee 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -27,33 +27,35 @@ public class AddBookEndpointSummary : Summary public AddBookEndpointSummary() { Summary = "Adds a new book."; - Description = "Creates a new book and returns its details, including the location of the newly created resource."; + Description = "Creates a new book and returns its details, including the location of the newly created resource. The request is handled by an Admin, who can add books to all libraries, or by the owner of the library."; + + Guid bookId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); ExampleRequest = new AddBookRequest( - LibraryId: Guid.NewGuid(), - Path: "/books/the-fellowship-of-the-ring.epub", + Path: "/media/libraries/books/the-fellowship-of-the-ring.pdf", Metadata: new( Title: "The Fellowship of the Ring", OriginalTitle: "The Fellowship of the Ring", Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", ReleaseInfo: new( - OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), + OriginalReleaseDate: new DateOnly(1954, 7, 29), OriginalReleaseYear: 1954, - ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), + ReReleaseDate: new DateOnly(2001, 9, 6), ReReleaseYear: 2001, ReleaseCountry: ReleaseCountry.GB, ReleaseVersion: "50th Anniversary Edition" ), - Genres: new List() { - { new(Name: "fantasy") }, - { new(Name: "adventure") }, - { new(Name: "classic") } - }, - Tags: new List() { - { new(Name: "epic fantasy") }, - { new(Name: "quest") }, - { new(Name: "middle-earth") } - }, + Genres: [ + new(Name: "fantasy"), + new(Name: "adventure"), + new(Name: "classic") + ], + Tags: [ + new(Name: "epic fantasy"), + new(Name: "quest"), + new(Name: "middle-earth") + ], Language: new( LanguageCode: "en", LanguageName: "English", @@ -71,7 +73,7 @@ public class AddBookEndpointSummary : Summary Format: BookFormat.Paperback, Edition: "50th Anniversary Edition", VolumeNumber: 1, - Series: new BookSeriesDto( + Series: new( Title: "The Lord of the Rings" ), ASIN: "B007978NPG", @@ -95,24 +97,12 @@ public class AddBookEndpointSummary : Summary ], Contributors: [ new( - Name: new MediaContributorNameDto( - DisplayName: "J.R.R. Tolkien", - LegalName: "John Ronald Reuel Tolkien" - ), - Role: new MediaContributorRoleDto( - Name: "author", - Category: MediaContributorRoleCategory.Author - ) + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Author ), new( - Name: new MediaContributorNameDto( - DisplayName: "Alan Lee", - LegalName: "Alan Lee" - ), - Role: new MediaContributorRoleDto( - Name: "illustrator", - Category: MediaContributorRoleCategory.Illustrator - ) + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Illustrator ) ], Ratings: [ @@ -131,8 +121,7 @@ public class AddBookEndpointSummary : Summary ] ); - RequestParam(r => r.LibraryId, "The Id of the media library this book belongs to. Required."); - RequestParam(r => r.Path, "The file system path of the book. Required."); + RequestParam(r => r.Path, "The file system path of the book. It must be inside one of the content locations of the media library that owns it. Required."); RequestParam(r => r.Metadata, "Written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the written content. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the written content, if different from the current title. Optional."); @@ -159,8 +148,8 @@ public class AddBookEndpointSummary : Summary RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional."); RequestParam(r => r.Edition, "The edition of the book. Optional."); RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional."); - RequestParam(r => r.Series, "The series name, if the book is part of a series. Optional."); - RequestParam(r => r.Series!.Title, "The title of the book series. Required."); + RequestParam(r => r.Series, "The series the book is part of. Book series are not yet supported and are ignored. Optional."); + RequestParam(r => r.Series!.Title, "The title of the book series. Book series are not yet supported and are ignored. Optional."); RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional."); RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional."); RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional."); @@ -171,7 +160,7 @@ public class AddBookEndpointSummary : Summary RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble Id of the book. Optional."); RequestParam(r => r.AppleBooksId, "The Apple Books Id of the book. Optional."); RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book. Required."); - RequestParam(r => r.Contributors, "The list of media contributors (actors, directors, etc) starring in this book. Required."); + RequestParam(r => r.Contributors, "The list of media contributors of the book. Required."); RequestParam(r => r.Ratings, "The list of ratings for this book. Required."); ResponseParam(r => r.Id, "The unique identifier of the book."); @@ -203,8 +192,8 @@ public class AddBookEndpointSummary : Summary ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); ResponseParam(r => r.Edition, "The edition of the book, if applicable."); ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); - ResponseParam(r => r.Series, "The series the book is part of, if applicable."); - ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null."); ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); @@ -215,7 +204,7 @@ public class AddBookEndpointSummary : Summary ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); - ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played."); ResponseParam(r => r.Ratings, "The list of ratings for the book."); ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); @@ -226,17 +215,17 @@ public class AddBookEndpointSummary : Summary Response(201, "The new book is returned.", example: new BookResponse( - Id: Guid.NewGuid(), - LibraryId: Guid.NewGuid(), - Path: "/books/the-fellowship-of-the-ring.epub", + Id: bookId, + LibraryId: libraryId, + Path: "/media/libraries/books/the-fellowship-of-the-ring.pdf", Metadata: new( Title: "The Fellowship of the Ring", OriginalTitle: "The Fellowship of the Ring", Description: "The first part of J.R.R. Tolkien's epic adventure The Lord of the Rings. In a sleepy village in the Shire, young Frodo Baggins finds himself faced with an immense task, as his elderly cousin Bilbo entrusts the Ring to his care. Frodo must leave his home and make a perilous journey across Middle-earth to the Cracks of Doom, there to destroy the Ring and foil the Dark Lord in his evil purpose.", ReleaseInfo: new( - OriginalReleaseDate: DateOnly.ParseExact("1954-07-29", "yyyy-MM-dd", null), + OriginalReleaseDate: new DateOnly(1954, 7, 29), OriginalReleaseYear: 1954, - ReReleaseDate: DateOnly.ParseExact("2001-09-06", "yyyy-MM-dd", null), + ReReleaseDate: new DateOnly(2001, 9, 6), ReReleaseYear: 2001, ReleaseCountry: ReleaseCountry.GB, ReleaseVersion: "50th Anniversary Edition" @@ -265,14 +254,11 @@ public class AddBookEndpointSummary : Summary ), Publisher: "Houghton Mifflin", PageCount: 398 - ), Format: BookFormat.Paperback, Edition: "50th Anniversary Edition", VolumeNumber: 1, - Series: new BookSeriesDto( - Title: "The Lord of the Rings" - ), + Series: null, ASIN: "B007978NPG", GoodreadsId: "3", LCCN: "54009621", @@ -294,24 +280,12 @@ public class AddBookEndpointSummary : Summary ], Contributors: [ new( - Name: new MediaContributorNameDto( - DisplayName: "J.R.R. Tolkien", - LegalName: "John Ronald Reuel Tolkien" - ), - Role: new MediaContributorRoleDto( - Name: "author", - Category: MediaContributorRoleCategory.Author - ) + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Author ), new( - Name: new MediaContributorNameDto( - DisplayName: "Alan Lee", - LegalName: "Alan Lee" - ), - Role: new MediaContributorRoleDto( - Name: "illustrator", - Category: MediaContributorRoleCategory.Illustrator - ) + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Illustrator ) ], Ratings: [ @@ -337,7 +311,6 @@ public class AddBookEndpointSummary : Summary ) ); - Response(401, "Authentication required.", "application/problem+json", example: new[] { @@ -346,16 +319,16 @@ public class AddBookEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", - instance = "/api/v1/books" + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books" }, new { type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", - instance = "/api/v1/books" + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books" }, new { @@ -363,7 +336,7 @@ public class AddBookEndpointSummary : Summary status = 401, title = "Unauthorized", detail = "The token is invalid", - instance = "/api/v1/books" + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books" } } ); @@ -375,11 +348,59 @@ public class AddBookEndpointSummary : Summary title = "General.Unauthorized", status = 403, detail = "NotAuthorized", - instance = "/api/v1/books", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books", traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" } ); + Response(404, "The request failed because the media library or one of the referenced media contributors does not exist.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "MediaContributorNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + + Response(409, "The request failed because a book with the same identity or path already exists.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "BookAlreadyExists", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + } + ); + Response(422, "The request did not pass validation checks.", "application/problem+json", example: new { @@ -387,14 +408,16 @@ public class AddBookEndpointSummary : Summary title = "General.Validation", status = 422, detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/books", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books", errors = new Dictionary { { "General.Validation", new[] { - "BookLibraryCannotBeNull", + "LibraryIdCannotBeEmpty", "BookPathCannotBeEmpty", + "BookPathMustBeMaximum2048CharactersLong", + "BookPathMustBeWithinLibraryContentLocations", "MetadataCannotBeNull", "TitleCannotBeEmpty", "TitleMustBeMaximum255CharactersLong", @@ -403,7 +426,6 @@ public class AddBookEndpointSummary : Summary "ReleaseInfoCannotBeNull", "OriginalReleaseYearMustBeBetween1And9999", "ReReleaseYearMustBeBetween1And9999", - "CountryCodeMustBe2CharactersLong", "ReleaseVersionMustBeMaximum50CharactersLong", "OriginalReleaseDateAndYearMustMatch", "ReReleaseDateAndYearMustMatch", @@ -442,14 +464,8 @@ public class AddBookEndpointSummary : Summary "InvalidIsbn10Format", "UnknownIsbnFormat", "ContributorsListCannotBeNull", - "ContributorNameCannotBeEmpty", - "ContributorDisplayNameCannotBeEmpty", - "ContributorDisplayNameMustBeMaximum100CharactersLong", - "ContributorLegalNameMustBeMaximum100CharactersLong", - "ContributorRoleCannotBeNull", - "RoleNameCannotBeEmpty", - "RoleNameMustBeMaximum50CharactersLong", - "RoleCategoryCannotBeEmpty", + "MediaContributorIdCannotBeEmpty", + "UnknownMediaContributorRole", "RatingsListCannotBeNull", "RatingValueMustBePositive", "RatingValueCannotBeGreaterThanMaxValue", diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs index 82981ea2..86e057da 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpoint.cs @@ -1,8 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; @@ -15,9 +14,9 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; /// -/// API endpoint for the /books/{id} route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId} route. /// -public class GetBookEndpoint : BaseEndpoint +public class GetBookEndpoint : BaseEndpoint { private readonly IQueryHandler> _getBookQueryHandler; @@ -35,20 +34,23 @@ public class GetBookEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(FastEndpoints.Http.GET); + Verbs(Http.GET); Routes(ApiRoutes.Books.GET_BOOK_BY_ID); Version(1); DontCatchExceptions(); } /// - /// Gets the book identified by . + /// Gets the book identified by the route. /// - /// The request containing the Id of the book to get. + /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - Result result = await _getBookQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + Result result = await _getBookQueryHandler.HandleAsync(new GetBookQuery(libraryId, bookId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs index f1b38187..cf06990a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointSummary.cs @@ -4,7 +4,6 @@ using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; @@ -20,7 +19,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetBookEndpointSummary : Summary +public class GetBookEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -28,13 +27,7 @@ public class GetBookEndpointSummary : Summary public GetBookEndpointSummary() { Summary = "Gets a book by its Id."; - Description = "Gets the full details of the book identified by the request, including the resolved names of its media contributors."; - - ExampleRequest = new GetBookRequest( - Id: Guid.NewGuid().ToString() - ); - - RequestParam(r => r.Id, "The Id of the book to get. Required."); + Description = "Gets the full details of the book identified by the route, including the references to its media contributors."; ResponseParam(r => r.Id, "The Id of the book."); ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to."); @@ -65,8 +58,8 @@ public class GetBookEndpointSummary : Summary ResponseParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); ResponseParam(r => r.Edition, "The edition of the book, if applicable."); ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); - ResponseParam(r => r.Series, "The series the book is part of, if applicable."); - ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null."); ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); @@ -77,7 +70,7 @@ public class GetBookEndpointSummary : Summary ResponseParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); - ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played."); ResponseParam(r => r.Ratings, "The list of ratings for the book."); ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); @@ -131,9 +124,7 @@ public class GetBookEndpointSummary : Summary Format: BookFormat.Paperback, Edition: "50th Anniversary Edition", VolumeNumber: 1, - Series: new BookSeriesDto( - Title: "The Lord of the Rings" - ), + Series: null, ASIN: "B007978NPG", GoodreadsId: "3", LCCN: "54009621", @@ -156,25 +147,13 @@ public class GetBookEndpointSummary : Summary ], Contributors: [ - new MediaContributorDto( - Name: new MediaContributorNameDto( - DisplayName: "J.R.R. Tolkien", - LegalName: "John Ronald Reuel Tolkien" - ), - Role: new MediaContributorRoleDto( - Name: "author", - Category: MediaContributorRoleCategory.Author - ) + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Author ), - new MediaContributorDto( - Name: new MediaContributorNameDto( - DisplayName: "Alan Lee", - LegalName: "Alan Lee" - ), - Role: new MediaContributorRoleDto( - Name: "illustrator", - Category: MediaContributorRoleCategory.Illustrator - ) + new MediaContributorReferenceDto( + ContributorId: Guid.NewGuid(), + Role: MediaContributorRole.Illustrator ) ], Ratings: @@ -202,13 +181,32 @@ public class GetBookEndpointSummary : Summary ); Response(401, "Authentication required.", "application/problem+json", - example: new + example: new[] { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "You are not authorized", - instance = "/api/v1/books/{id}" + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}" + } } ); @@ -219,7 +217,7 @@ public class GetBookEndpointSummary : Summary title = "General.Unauthorized", status = 403, detail = "NotAuthorized", - instance = "/api/v1/books/{id}", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}", traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" } ); @@ -231,7 +229,7 @@ public class GetBookEndpointSummary : Summary title = "General.NotFound", status = 404, detail = "BookNotFound", - instance = "/api/v1/books/{id}", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}", traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" } ); @@ -243,12 +241,13 @@ public class GetBookEndpointSummary : Summary title = "General.Validation", status = 422, detail = "OneOrMoreValidationErrorsOccurred", - instance = "/api/v1/books/{id}", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}", errors = new Dictionary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty" } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs index 47183f75..bb76e864 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpoint.cs @@ -18,7 +18,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; /// -/// API endpoint for the /books route. +/// API endpoint for the /libraries/{libraryId}/books route. /// public class GetBooksEndpoint : BaseEndpoint { @@ -45,13 +45,15 @@ public class GetBooksEndpoint : BaseEndpoint } /// - /// Gets the list of all the books of the media library identified by . + /// Gets the list of all the books of the media library identified by the libraryId route parameter. /// - /// The request containing the Id of the media library whose books are retrieved. + /// The request containing the filtering and pagination options of the books to be retrieved. /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksRequest request, CancellationToken cancellationToken) { - Result> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getBooksQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs index 1d3841f1..e3b99c9f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointSummary.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; @@ -27,25 +27,29 @@ public class GetBooksEndpointSummary : Summary public GetBooksEndpointSummary() { - Summary = "Retrieves the list of books."; - Description = "Returns the entire list of books."; + Summary = "Retrieves the list of books of a media library."; + Description = "Returns the paginated, filterable list of the books of the media library identified by the route, with the full details of each book. The page is returned to an Admin, who can see the books of all libraries, or to the owner of the library."; ExampleRequest = new GetBooksRequest( - LibraryId: Guid.NewGuid(), CurrentPage: 1, - PerPage: 48, + PerPage: 10, SearchTerm: "fellowship", SortBy: "title", SortOrder: SortOrder.Ascending ); - RequestParam(r => r.LibraryId, "The Id of the media library whose books are retrieved. Required."); RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); + ResponseParam>(r => r.Data, "The books on the current page, each with the full details of the book."); + ResponseParam>(r => r.CurrentPage, "The current page number."); + ResponseParam>(r => r.PerPage, "The number of books retrieved per page."); + ResponseParam>(r => r.Count, "The total number of books matching the request."); + ResponseParam>(r => r.NumberOfPages, "The total number of pages."); + Response(200, "The paginated list of books is returned.", example: new PaginatedResponse { @@ -93,9 +97,7 @@ public class GetBooksEndpointSummary : Summary { { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs index 51341186..ab69877e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpoint.cs @@ -17,7 +17,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; /// -/// API endpoint for the /books/lite route. +/// API endpoint for the /libraries/{libraryId}/books/lite route. /// public class GetBooksLiteEndpoint : BaseEndpoint { @@ -44,13 +44,15 @@ public class GetBooksLiteEndpoint : BaseEndpoint } /// - /// Gets the lightweight details of all the books of the media library identified by . + /// Gets the lightweight details of all the books of the media library identified by the libraryId route parameter. /// - /// The request containing the Id of the media library whose books are retrieved. + /// The request containing the filtering and pagination options of the books to be retrieved. /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBooksLiteRequest request, CancellationToken cancellationToken) { - Result> result = await _getBooksLiteQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + Result> result = await _getBooksLiteQueryHandler.HandleAsync(request.ToQuery(libraryId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs index 14be3df3..6d53682a 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointSummary.cs @@ -22,13 +22,12 @@ public class GetBooksLiteEndpointSummary : Summary public GetBooksLiteEndpointSummary() { - Summary = "Retrieves the lightweight details of the list of books."; - Description = "Returns a paginated list of the lightweight details of the books of the media library, suitable for card-style navigation."; + Summary = "Retrieves the list of lightweight book details of a media library."; + Description = "Returns the paginated, filterable list of the lightweight details of the books of the media library identified by the route, suitable for card-style navigation. The page is returned to an Admin, who can see the books of all libraries, or to the owner of the library."; ExampleRequest = new GetBooksLiteRequest( - LibraryId: Guid.NewGuid(), CurrentPage: 1, - PerPage: 48, + PerPage: 10, SearchTerm: "fellowship", FilterAlphaKey: "f", ShouldIgnoreThePrefixForAlphaPicker: true, @@ -36,7 +35,6 @@ public class GetBooksLiteEndpointSummary : Summary r.LibraryId, "The Id of the media library whose books are retrieved. Required."); RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); RequestParam(r => r.PerPage, "The maximum number of books to retrieve per page. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); @@ -45,6 +43,12 @@ public class GetBooksLiteEndpointSummary : Summary r.SortBy, "The name of the field by which to sort the results. Optional."); RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); + ResponseParam>(r => r.Data, "The lightweight book details on the current page."); + ResponseParam>(r => r.CurrentPage, "The current page number."); + ResponseParam>(r => r.PerPage, "The number of books retrieved per page."); + ResponseParam>(r => r.Count, "The total number of books matching the request."); + ResponseParam>(r => r.NumberOfPages, "The total number of pages."); + Response(200, "The paginated list of lightweight book details is returned.", example: new PaginatedResponse { @@ -77,16 +81,16 @@ public class GetBooksLiteEndpointSummary : Summary { { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs index 45beb694..c99500f6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; @@ -16,9 +13,9 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; /// -/// API endpoint for the /books/{bookId}/reading/availability route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId}/reading/availability route. /// -public class GetReadingAvailabilityEndpoint : BaseEndpoint +public class GetReadingAvailabilityEndpoint : BaseEndpoint { private readonly IQueryHandler> _getReadingAvailabilityQueryHandler; @@ -36,20 +33,24 @@ public class GetReadingAvailabilityEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY); Version(1); DontCatchExceptions(); } /// - /// Checks the reading availability of the book identified by . + /// Checks the reading availability of the book identified by the route. /// - /// The request containing the Id of the book whose reading availability is checked. + /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetReadingAvailabilityRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { - Result result = await _getReadingAvailabilityQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + GetReadingAvailabilityQuery query = new(libraryId, bookId); + Result result = await _getReadingAvailabilityQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs index 7b81fa89..5fcde058 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using System; using System.Collections.Generic; @@ -13,7 +12,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetReadingAvailabilityEndpointSummary : Summary +public class GetReadingAvailabilityEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -23,12 +22,6 @@ public class GetReadingAvailabilityEndpointSummary : Summary r.BookId, "The Id of the book whose reading availability is checked. Required."); - ResponseParam(r => r.BookId, "The Id of the book whose reading availability is reported."); ResponseParam(r => r.LibraryId, "The Id of the media library the book belongs to."); ResponseParam(r => r.IsAvailable, "Whether the book can be opened for reading."); @@ -44,13 +37,32 @@ public class GetReadingAvailabilityEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty" } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs index bf39836b..739d74d0 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; @@ -16,9 +13,9 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; /// -/// API endpoint for the /books/{bookId}/reading/manifest route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId}/reading/manifest route. /// -public class GetReadingManifestEndpoint : BaseEndpoint +public class GetReadingManifestEndpoint : BaseEndpoint { private readonly IQueryHandler> _getReadingManifestQueryHandler; @@ -36,20 +33,24 @@ public class GetReadingManifestEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOK_READING_MANIFEST); Version(1); DontCatchExceptions(); } /// - /// Gets the reading manifest of the book identified by . + /// Gets the reading manifest of the book identified by the route. /// - /// The request containing the Id of the book whose reading manifest is retrieved. + /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetReadingManifestRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { - Result result = await _getReadingManifestQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + GetReadingManifestQuery query = new(libraryId, bookId); + Result result = await _getReadingManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs index 4371ce0f..722ccc61 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using System; using System.Collections.Generic; @@ -13,7 +12,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetReadingManifestEndpointSummary : Summary +public class GetReadingManifestEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -23,16 +22,16 @@ public class GetReadingManifestEndpointSummary : Summary r.BookId, "The Id of the book whose reading manifest is retrieved. Required."); - ResponseParam(r => r.Title, "The title of the book."); ResponseParam(r => r.Author, "The author of the book, if known."); ResponseParam(r => r.CoverResourceKey, "The resource key of the cover image of the book, if applicable."); + ResponseParam(r => r.TableOfContents, "The hierarchical table of contents of the book."); + ResponseParam(r => r.TableOfContents[0].Label, "The label of the table of contents entry."); + ResponseParam(r => r.TableOfContents[0].LocationRef, "The opaque location reference of the reading section the entry points to."); + ResponseParam(r => r.TableOfContents[0].Children, "The child entries of the table of contents entry."); ResponseParam(r => r.Spine, "The ordered spine of the reading sections of the book."); + ResponseParam(r => r.Spine[0].LocationRef, "The opaque location reference of the reading section."); + ResponseParam(r => r.Spine[0].Title, "The title of the reading section, if known."); ResponseParam(r => r.ResourceKeys, "The resource keys of the resources of the book."); ResponseParam(r => r.HasTextContent, "Whether the book has extractable text content. A scanned book, whose pages are only images, has no text content."); @@ -62,13 +61,32 @@ public class GetReadingManifestEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty" } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs index 26cf512d..af0f35b0 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs @@ -1,10 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; @@ -17,9 +14,9 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; /// -/// API endpoint for the /books/{bookId}/reading/resources/{resourceKey} route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId}/reading/resources/{resourceKey} route. /// -public class GetReadingResourceEndpoint : BaseEndpoint +public class GetReadingResourceEndpoint : BaseEndpoint { private readonly IQueryHandler> _getReadingResourceQueryHandler; @@ -37,20 +34,25 @@ public class GetReadingResourceEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOK_READING_RESOURCE); Version(1); DontCatchExceptions(); } /// - /// Gets the resource of the book identified by . + /// Gets the resource of the book identified by the route. /// - /// The request containing the Id of the book and the resource key of the resource. + /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetReadingResourceRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { - Result result = await _getReadingResourceQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + string? resourceKey = HttpContext.Request.RouteValues["resourceKey"]?.ToString(); + GetReadingResourceQuery query = new(libraryId, bookId, resourceKey); + Result result = await _getReadingResourceQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); if (result.IsFailure) return Problem(result.Errors); // The media type of a resource is declared by the book itself, so it is not trusted: a resource whose declared media type could be diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs index c624beea..19075ffe 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -12,7 +11,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetReadingResourceEndpointSummary : Summary +public class GetReadingResourceEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -22,24 +21,35 @@ public class GetReadingResourceEndpointSummary : Summary r.BookId, "The Id of the book whose resource is retrieved. Required."); - RequestParam(r => r.ResourceKey, "The opaque resource key of the resource. Required."); - - Response(200, "The resource of the book is returned."); + Response(200, "The binary resource of the book is returned, with the media type of the resource, or application/octet-stream for media types that could be rendered as active documents.", "*/*"); Response(401, "Authentication required.", "application/problem+json", - example: new + example: new[] { - type = "https://tools.ietf.org/html/rfc7235#section-3.1", - status = 401, - title = "Unauthorized", - detail = "You are not authorized", - instance = "/api/v1/books/{bookId}/reading/resources/{resourceKey}" + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover-image" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover-image" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/cover-image" + } } ); @@ -47,23 +57,71 @@ public class GetReadingResourceEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty", "ResourceKeyCannotBeEmpty" } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs index d5ee709a..348377f7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs @@ -1,10 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Api.Core.Endpoints.Common; @@ -16,9 +13,9 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; /// -/// API endpoint for the /books/{bookId}/reading/sections/{locationRef} route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef} route. /// -public class GetReadingSectionEndpoint : BaseEndpoint +public class GetReadingSectionEndpoint : BaseEndpoint { private readonly IQueryHandler> _getReadingSectionQueryHandler; @@ -36,20 +33,25 @@ public class GetReadingSectionEndpoint : BaseEndpoint public override void Configure() { - Verbs(Http.GET); + Verbs(FastEndpoints.Http.GET); Routes(ApiRoutes.Books.GET_BOOK_READING_SECTION); Version(1); DontCatchExceptions(); } /// - /// Gets the content of the reading section of the book identified by . + /// Gets the content of the reading section of the book identified by the route. /// - /// The request containing the Id of the book and the location reference of the reading section. + /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetReadingSectionRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { - Result result = await _getReadingSectionQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + string? locationRef = HttpContext.Request.RouteValues["locationRef"]?.ToString(); + GetReadingSectionQuery query = new(libraryId, bookId, locationRef); + Result result = await _getReadingSectionQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs index 2ede5f39..f4f52c60 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -13,7 +12,7 @@ namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.B /// Class used for providing a textual description for the API endpoint, for OpenAPI. /// [ExcludeFromCodeCoverage] -public class GetReadingSectionEndpointSummary : Summary +public class GetReadingSectionEndpointSummary : Summary { /// /// Initializes a new instance of the class. @@ -23,14 +22,6 @@ public class GetReadingSectionEndpointSummary : Summary r.BookId, "The Id of the book whose reading section is retrieved. Required."); - RequestParam(r => r.LocationRef, "The opaque location reference of the reading section. Required."); - ResponseParam(r => r.LocationRef, "The opaque location reference of the reading section."); ResponseParam(r => r.Title, "The title of the reading section, if known."); ResponseParam(r => r.ContentHtml, "The sanitized HTML content of the reading section."); @@ -44,13 +35,32 @@ public class GetReadingSectionEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty", "LocationRefCannotBeEmpty" } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs index 07c489b2..17423e1d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpoint.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; /// -/// API endpoint for the /books/{id} route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId} route. /// public class UpdateBookEndpoint : BaseEndpoint { @@ -48,12 +48,10 @@ public class UpdateBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) { - // The book is identified by the {id} route value, not by the id of the request body, so that a mismatched or malicious id can never - // redirect the update to another book; the raw value is kept as a string, so that an unparseable id reaches the command validator, - // which reports it with a ProblemDetails validation error instead of failing the request binding. - request = request with { Id = HttpContext.Request.RouteValues["id"]?.ToString() }; - - Result result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + // Take unique identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); + Result result = await _updateBookCommandHandler.HandleAsync(request.ToCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs index 6d42a2b0..0f9c109b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointSummary.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; @@ -27,10 +27,9 @@ public class UpdateBookEndpointSummary : Summary public UpdateBookEndpointSummary() { - Summary = "Updates a book."; - Description = "Updates the details of the book identified by the request."; + Summary = "Updates an existing book."; + Description = "Updates the details of the book identified by the route, returning the full details of the updated book. The book is updated by an Admin, who can update the books of all libraries, or by the owner of the library of the book."; - RequestParam(r => r.Id, "The Id of the book to update. Required."); RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional."); @@ -45,20 +44,20 @@ public class UpdateBookEndpointSummary : Summary r.Metadata!.Genres, "The list of genres of the book. Required."); RequestParam(r => r.Metadata!.Tags, "The list of tags of the book. Required."); RequestParam(r => r.Metadata!.Language, "The language in which the book is written. Optional."); - RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book. Optional."); - RequestParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageCode, "The ISO code of the language of the book. Required."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The name of the language of the book in English. Required."); RequestParam(r => r.Metadata!.Language!.NativeName, "The native name of the language of the book. Optional."); RequestParam(r => r.Metadata!.OriginalLanguage, "The original language of the book, if it has been translated. Optional."); - RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book. Optional."); - RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageCode, "The ISO code of the original language of the book. Required."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The name of the original language of the book in English. Required."); RequestParam(r => r.Metadata!.OriginalLanguage!.NativeName, "The native name of the original language of the book. Optional."); RequestParam(r => r.Metadata!.Publisher, "The publisher of the book. Optional."); RequestParam(r => r.Metadata!.PageCount, "The number of pages of the book. Optional."); RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback). Optional."); RequestParam(r => r.Edition, "The edition of the book. Optional."); RequestParam(r => r.VolumeNumber, "The volume or book number in the series. Optional."); - RequestParam(r => r.Series, "The series the book is part of. Optional."); - RequestParam(r => r.Series!.Title, "The title of the series the book is part of. Optional."); + RequestParam(r => r.Series, "The series the book is part of. Book series are not yet supported and are ignored. Optional."); + RequestParam(r => r.Series!.Title, "The title of the book series. Book series are not yet supported and are ignored. Optional."); RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book. Optional."); RequestParam(r => r.GoodreadsId, "The Goodreads Id of the book. Optional."); RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book. Optional."); @@ -73,7 +72,6 @@ public class UpdateBookEndpointSummary : Summary r.Ratings, "The list of ratings of the book. Required."); ExampleRequest = new UpdateBookRequest( - Id: Guid.NewGuid().ToString(), Metadata: new WrittenContentMetadataDto( Title: "The Fellowship of the Ring", OriginalTitle: "The Fellowship of the Ring", @@ -139,25 +137,13 @@ public class UpdateBookEndpointSummary : Summary(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable."); ResponseParam(r => r.Edition, "The edition of the book, if applicable."); ResponseParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable."); - ResponseParam(r => r.Series, "The series the book is part of, if applicable."); - ResponseParam(r => r.Series!.Title, "The title of the series the book is part of."); + ResponseParam(r => r.Series, "The series the book is part of. Book series are not yet supported and this is always null."); + ResponseParam(r => r.Series!.Title, "The title of the series the book is part of. Book series are not yet supported and this is always null."); ResponseParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable."); ResponseParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable."); ResponseParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable."); @@ -218,7 +204,7 @@ public class UpdateBookEndpointSummary : Summary(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable."); ResponseParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable."); ResponseParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book."); - ResponseParam(r => r.Contributors, "The list of media contributors starring in this book."); + ResponseParam(r => r.Contributors, "The list of references to the media contributors that contributed to this book, each with the role they played."); ResponseParam(r => r.Ratings, "The list of ratings for the book."); ResponseParam(r => r.MetadataStatus, "The status of the metadata enrichment of the book."); ResponseParam(r => r.LastMetadataUpdateUtc, "The date and time when the metadata of the book was last enriched, if applicable."); @@ -272,9 +258,7 @@ public class UpdateBookEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty", "MetadataCannotBeNull", "TitleCannotBeEmpty", @@ -399,7 +424,6 @@ public class UpdateBookEndpointSummary : Summary -/// API endpoint for the /books/{id}/cover route. +/// API endpoint for the /libraries/{libraryId}/books/{bookId}/cover route. /// -public class UpdateBookCoverEndpoint : BaseEndpoint +public class UpdateBookCoverEndpoint : BaseEndpoint { - private readonly Application.Common.CQRS.ICommandHandler> _updateBookCoverCommandHandler; + private readonly ICommandHandler> _updateBookCoverCommandHandler; /// /// Initializes a new instance of the class. /// /// Injected service for handling update book cover commands. - public UpdateBookCoverEndpoint(Application.Common.CQRS.ICommandHandler> updateBookCoverCommandHandler) + public UpdateBookCoverEndpoint(ICommandHandler> updateBookCoverCommandHandler) { _updateBookCoverCommandHandler = updateBookCoverCommandHandler; } @@ -34,7 +35,7 @@ public class UpdateBookCoverEndpoint : BaseEndpoint /// public override void Configure() { - Verbs(Http.PUT); + Verbs(FastEndpoints.Http.PUT); Routes(ApiRoutes.Books.UPDATE_BOOK_COVER); Version(1); DontCatchExceptions(); @@ -45,11 +46,11 @@ public class UpdateBookCoverEndpoint : BaseEndpoint /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { - // The endpoint takes no typed request, because its body is a multipart file, so the book id is read from the {id} route - // value; an unparseable value becomes Guid.Empty, which the command validator reports as a missing book id. - Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["id"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty; + // Take the identifiers from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString(); IFormFile? cover = null; if (HttpContext.Request.HasFormContentType) @@ -67,10 +68,10 @@ public class UpdateBookCoverEndpoint : BaseEndpoint } // The cover stream must stay open while the handler stores the image, and is disposed as soon as the handler returns. - UpdateBookCoverCommand command = new(bookId, cover?.OpenReadStream(), cover?.FileName); + UpdateBookCoverCommand command = new(libraryId, bookId, cover?.OpenReadStream(), cover?.FileName); try { - Result result = await _updateBookCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); + Result result = await _updateBookCoverCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } finally diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs index a7f89cfe..0c00d84e 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -18,20 +20,41 @@ public class UpdateBookCoverEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty", "BookCoverCannotBeNull", + "FileNameCannotBeEmpty", "FileTooLarge", "CoverFileMustBeAnImage" } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs index 873837ad..8bbd5e38 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Maintenance/CheckHealthEndpoint.cs @@ -10,7 +10,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance; /// -/// API endpoint for the /directories/get-directories route. +/// API endpoint for the /check-health route. /// public class CheckHealthEndpoint : BaseEndpoint { @@ -32,7 +32,7 @@ public class CheckHealthEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken) { - // TODO: to be implemented + // TODO: to be implemented. return await Task.FromResult(TypedResults.Ok()); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs index d8618092..e45a503f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs @@ -60,7 +60,7 @@ public class GetLibraryArtworkProvidersEndpointSummary : Summary -/// API endpoint for the /themes/{themeId}/assets/{assetPath} route. +/// API endpoint for the /themes/{themeId}/assets/{*assetPath} route. /// public class GetThemeAssetEndpoint : BaseEndpoint { @@ -39,7 +39,7 @@ public class GetThemeAssetEndpoint : BaseEndpoint Verbs(Http.GET); Routes(ApiRoutes.Themes.GET_THEME_ASSET); Version(1); - // theme content is public, since the web renders themed pages for anonymous visitors too (i.e.: login page); only install and manage operations are admin-gated + // Theme content is public, since the web renders themed pages for anonymous visitors too (i.e.: login page); only install and manage operations are admin-gated. AllowAnonymous(); DontCatchExceptions(); } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs index 2faaeadb..7711c040 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointSummary.cs @@ -60,7 +60,7 @@ public class GetThemesEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", + detail = "Authentication failed", instance = "/api/v1/themes" }, new @@ -68,7 +68,7 @@ public class GetThemesEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + detail = "The token has expired", instance = "/api/v1/themes" }, new diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs index f63eb8dc..060740e6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointSummary.cs @@ -47,7 +47,7 @@ public class ChangePasswordEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "You are not authorized", + detail = "Authentication failed", instance = "/api/v1/auth/users" }, new @@ -42,7 +42,7 @@ public class GetUsersEndpointSummary : Summary type = "https://tools.ietf.org/html/rfc7235#section-3.1", status = 401, title = "Unauthorized", - detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + detail = "The token has expired", instance = "/api/v1/auth/users" }, new diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs index 1de71e92..062e5e36 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointSummary.cs @@ -45,7 +45,7 @@ public class GetAuthorizationEndpointSummary : Summary { { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs index 4097e948..9761783b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointSummary.cs @@ -44,7 +44,7 @@ public class GetUserRoleEndpointSummary : Summary /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The stream of the file to upload. - /// The name of the file to upload. + /// The stream of the file to upload, or to send a multipart form without any file. + /// The name of the file to upload, or when no file is sent. /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - public async Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) + public async Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default) { - // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. using MultipartFormDataContent form = []; - using StreamContent fileContent = new(fileStream); - fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); - form.Add(fileContent, fieldName, fileName); + if (fileStream is not null) + { + // The file is streamed as a generic binary part, since the exact content type of the uploaded file is not known. + StreamContent fileContent = new(fileStream); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + form.Add(fileContent, fieldName, fileName ?? string.Empty); + } using HttpRequestMessage request = new(HttpMethod.Put, endpoint) { diff --git a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs index ae7d9d45..77bae8cd 100644 --- a/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs +++ b/src/Lumina.Presentation.Web/Common/Api/IApiHttpClient.cs @@ -62,12 +62,12 @@ public interface IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The stream of the file to upload. - /// The name of the file to upload. + /// The stream of the file to upload, or to send a multipart form without any file. + /// The name of the file to upload, or when no file is sent. /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default); + Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default); /// /// Sends a POST request with a multipart form containing a single file to the specified as an asynchronous operation and returns the result. diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs index 2790c5b0..e8b50622 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/ErrorViewDto.cs @@ -5,7 +5,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Common; /// /// Data transfer object for the data shown on the error page. /// -[DebuggerDisplay("RequestId: {RequestId}, ShowRequestId: {ShowRequestId}")] +[DebuggerDisplay("RequestId: {RequestId}, ShouldShowRequestId: {ShouldShowRequestId}")] public class ErrorViewDto { /// @@ -16,5 +16,5 @@ public class ErrorViewDto /// /// Gets a value indicating whether the request identifier should be shown. /// - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + public bool ShouldShowRequestId => !string.IsNullOrEmpty(RequestId); } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs index b776c4e1..3611541b 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponse.cs @@ -7,7 +7,7 @@ namespace Lumina.Presentation.Web.Common.DTO.Common; /// /// Response data transfer object for the JSON responses of the web application that do not carry a payload. /// -/// Whether the operation succeeded or not. +/// Whether the operation succeeded or not. public record SuccessResponse( - [property: JsonPropertyName("success")] bool Success + [property: JsonPropertyName("success")] bool IsSuccess ); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs index 70e8e767..c1cef521 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Common/SuccessResponseOfT.cs @@ -8,9 +8,9 @@ namespace Lumina.Presentation.Web.Common.DTO.Common; /// Response data transfer object for the JSON responses of the web application that carry a payload. /// /// The type of the payload of the response. -/// Whether the operation succeeded or not. +/// Whether the operation succeeded or not. /// The payload of the response. public record SuccessResponse( - [property: JsonPropertyName("success")] bool Success, + [property: JsonPropertyName("success")] bool IsSuccess, [property: JsonPropertyName("data")] TData? Data ); diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs index 97587776..63a0996a 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.MediaContributors; using System.Diagnostics; #endregion @@ -16,7 +17,7 @@ public class MediaContributorDto public MediaContributorNameDto? Name { get; set; } /// - /// Gets the role of the contributor. + /// Gets the canonical role of the contributor, used as the key of its localized display string. /// - public MediaContributorRoleDto? Role { get; set; } + public MediaContributorRole? Role { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorRoleDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorRoleDto.cs deleted file mode 100644 index 74eaf370..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/MediaContributors/MediaContributorRoleDto.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.MediaContributors; - -/// -/// Data transfer object for a media contributor role. -/// -[DebuggerDisplay("Name: {Name}")] -public class MediaContributorRoleDto -{ - /// - /// Gets the value representing this object. - /// - public string? Name { get; set; } - - /// - /// Gets the category of this object. - /// - public string? Category { get; set; } -} diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs index 7fbc3876..da284cff 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeSectionNodeDto.cs @@ -9,11 +9,11 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// Data transfer object for a conditional or repeating section in a theme template. /// /// The property path expression that controls the section. -/// Whether the section renders when the resolved value is falsy instead of truthy. +/// Whether the section renders when the resolved value is falsy instead of truthy. /// The template nodes rendered when the section is active. [DebuggerDisplay("Expression: {Expression}")] public sealed record ThemeSectionNodeDto( string Expression, - bool Inverted, + bool IsInverted, IReadOnlyList Children ) : ThemeTemplateNodeDto; diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs index cce23ee3..17d58a39 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs @@ -196,7 +196,7 @@ public class BookDto public List ISBNs { get; set; } = []; /// - /// Gets the list of media contributors (actors, directors, etc) starring in this book. + /// Gets the list of media contributors that contributed to this book. /// //public List ContributorIds { get; init; } = []; diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDto.cs new file mode 100644 index 00000000..26c98283 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Data transfer object for the response of an update book cover operation. +/// +[DebuggerDisplay("CoverPath: {CoverPath}")] +public class UpdateBookCoverDto +{ + /// + /// Gets or sets the relative path of the stored cover image. + /// + public string? CoverPath { get; set; } +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/MediaContributors/MediaContributorRole.cs b/src/Lumina.Presentation.Web/Common/Enums/MediaContributors/MediaContributorRole.cs new file mode 100644 index 00000000..85935017 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/MediaContributors/MediaContributorRole.cs @@ -0,0 +1,175 @@ +namespace Lumina.Presentation.Web.Common.Enums.MediaContributors; + +/// +/// Enumeration for the role of a media contributor in a media item. +/// The role is used as the key of the localized display strings of the UI, and normalizes the free-form role names +/// returned by the metadata providers, so that roles that describe the same kind of contribution, like "Author" and +/// "Writer", are never treated as distinct. +/// +public enum MediaContributorRole +{ + /// + /// The role does not fall into any of the known roles. + /// + Other, + + /// + /// The contributor wrote the media item, like a book, a movie, or a piece of music. + /// + Author, + + /// + /// The contributor translated the media item into another language. + /// + Translator, + + /// + /// The contributor created the illustrations of the media item. + /// + Illustrator, + + /// + /// The contributor published the media item. + /// + Publisher, + + /// + /// The contributor narrated the media item. + /// + Narrator, + + /// + /// The contributor played a role in a filmed media item. + /// + Actor, + + /// + /// The contributor directed a filmed media item. + /// + Director, + + /// + /// The contributor wrote the screenplay of a filmed media item. + /// + Screenwriter, + + /// + /// The contributor wrote the music of the media item. + /// + Composer, + + /// + /// The contributor wrote the lyrics of the media item. + /// + Lyricist, + + /// + /// The contributor arranged the music of the media item. + /// + Arranger, + + /// + /// The contributor conducted the ensemble performing the media item. + /// + Conductor, + + /// + /// The contributor oversaw the production of the media item. + /// + Producer, + + /// + /// The contributor oversaw the overall production of the media item, rather than a single track or episode. + /// + ExecutiveProducer, + + /// + /// The contributor operated the recording equipment during the production of the media item. + /// + Engineer, + + /// + /// The contributor mixed the audio of the media item. + /// + Mixer, + + /// + /// The contributor created a remix of the media item. + /// + Remixer, + + /// + /// The contributor released the media item under a record label. + /// + RecordLabel, + + /// + /// The contributor sang the media item. + /// + Vocals, + + /// + /// The contributor sang the backing vocals of the media item. + /// + BackingVocals, + + /// + /// The contributor played the guitar in the media item. + /// + Guitar, + + /// + /// The contributor played the bass guitar in the media item. + /// + BassGuitar, + + /// + /// The contributor played the drums in the media item. + /// + Drums, + + /// + /// The contributor played percussion in the media item. + /// + Percussion, + + /// + /// The contributor played the keyboards in the media item. + /// + Keyboards, + + /// + /// The contributor played the piano in the media item. + /// + Piano, + + /// + /// The contributor played the synthesizer in the media item. + /// + Synthesizer, + + /// + /// The contributor played a string instrument in the media item. + /// + Strings, + + /// + /// The contributor played a woodwind instrument in the media item. + /// + Woodwinds, + + /// + /// The contributor played a brass instrument in the media item. + /// + Brass, + + /// + /// The contributor sang in a choir in the media item. + /// + Choir, + + /// + /// The contributor orchestrated the music of the media item. + /// + Orchestrator +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs index 6319e090..8ba7aa2d 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequest.cs @@ -8,9 +8,9 @@ namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directori /// Represents a request to get the directories of a file system path. /// /// The file system path for which to get the directories. Required. -/// Whether to include hidden file system elements or not. Optional. +/// Whether to include hidden file system elements or not. Optional. [DebuggerDisplay("Path: {Path}")] public record GetDirectoriesRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs index 0448d103..2ac7cdf1 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetFilesRequest.cs @@ -8,9 +8,9 @@ namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; /// Represents a request to get the files at a file system path. /// /// The file system path for which to get the files. Required. -/// Whether to include hidden file system elements or not. Optional. +/// Whether to include hidden file system elements or not. Optional. [DebuggerDisplay("Path: {Path}")] public record GetFilesRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs index f78a9dcc..f08b0c47 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Files/GetTreeFilesRequest.cs @@ -8,9 +8,9 @@ namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Files; /// Represents a request to get the files of a file system path. /// /// The file system path for which to get the tree files. Required. -/// Whether to include hidden file system elements or not. Optional. +/// Whether to include hidden file system elements or not. Optional. [DebuggerDisplay("Path: {Path}")] public record GetTreeFilesRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs index 78fb23a8..98ec593a 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/FileSystemManagement/Path/CheckPathExistsRequest.cs @@ -8,9 +8,9 @@ namespace Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; /// Represents a request to check the existence of a file system path. /// /// The file system path to check the exitence of. Required. -/// Whether to include hidden elements in the search results, or not. Optional. -[DebuggerDisplay("Path: {Path}, IncludeHiddenElements: {IncludeHiddenElements}")] +/// Whether to include hidden elements in the search results, or not. Optional. +[DebuggerDisplay("Path: {Path}, ShouldIncludeHiddenElements: {ShouldIncludeHiddenElements}")] public record CheckPathExistsRequest( string? Path, - bool IncludeHiddenElements + bool ShouldIncludeHiddenElements ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs index eff995d1..8668c6ae 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBookRequest.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using System; using System.Diagnostics; #endregion @@ -7,8 +8,10 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// Represents a request to get a book by the specified Id. /// -/// The unique identifier of the book to retrieve, taken from the route. Required. -[DebuggerDisplay("Id: {Id}")] +/// The unique identifier of the book to retrieve, taken from the route. Required. +/// The Id of the media library the book belongs to. Required. +[DebuggerDisplay("BookId: {BookId}")] public record GetBookRequest( - string Id + string BookId, + Guid LibraryId ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs index 2dfe972b..e633e455 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequest.cs @@ -9,7 +9,9 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// Represents a request to check the reading availability of a book. /// /// The unique identifier of the book whose reading availability is checked. Required. +/// The Id of the media library the book belongs to. Required. [DebuggerDisplay("BookId: {BookId}")] public record GetBookReadingAvailabilityRequest( - Guid BookId + Guid BookId, + Guid LibraryId ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs index 51bcd1ae..529672b0 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequest.cs @@ -9,7 +9,9 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// Represents a request to get the reading manifest of a book. /// /// The unique identifier of the book whose reading manifest is retrieved. Required. +/// The Id of the media library the book belongs to. Required. [DebuggerDisplay("BookId: {BookId}")] public record GetBookReadingManifestRequest( - Guid BookId + Guid BookId, + Guid LibraryId ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs index e9fc548e..bafcbf83 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequest.cs @@ -10,8 +10,10 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// The unique identifier of the book whose resource is retrieved. Required. /// The opaque resource key of the resource. Required. +/// The Id of the media library the book belongs to. Required. [DebuggerDisplay("BookId: {BookId}, ResourceKey: {ResourceKey}")] public record GetBookReadingResourceRequest( Guid BookId, - string ResourceKey + string ResourceKey, + Guid LibraryId ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs index b26565d8..2bc2d9b6 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequest.cs @@ -10,8 +10,10 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// /// The unique identifier of the book whose reading section is retrieved. Required. /// The opaque location reference of the reading section. Required. +/// The Id of the media library the book belongs to. Required. [DebuggerDisplay("BookId: {BookId}, LocationRef: {LocationRef}")] public record GetBookReadingSectionRequest( Guid BookId, - string LocationRef + string LocationRef, + Guid LibraryId ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs index 55a73d55..0db696f3 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequest.cs @@ -9,7 +9,9 @@ namespace Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// Represents the request for displaying the reading view of a book. /// /// The unique identifier of the book to read. Required. +/// The Id of the media library the book belongs to. Required. [DebuggerDisplay("BookId: {BookId}")] public record ReadBookViewRequest( - Guid BookId + Guid BookId, + Guid LibraryId ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs index 29ec1889..ca5fb674 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.DTO.MediaContributors; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using System; using System.Collections.Generic; using System.Diagnostics; #endregion @@ -18,7 +19,12 @@ public class UpdateBookRequest /// /// Gets or sets the Id of the book to update, taken from the route. /// - public string? Id { get; set; } + public string? BookId { get; set; } + + /// + /// Gets or sets the Id of the media library the book belongs to. + /// + public Guid LibraryId { get; set; } /// /// Gets or sets the written content metadata of the book. @@ -96,7 +102,7 @@ public class UpdateBookRequest public List? ISBNs { get; set; } /// - /// Gets or sets the list of media contributors of the book. + /// Gets or sets the list of media contributors of the book. Required. /// public List? Contributors { get; set; } diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs index 5956a3b3..1dbdba05 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Books.cs @@ -10,13 +10,13 @@ public static partial class ApiRoutes /// public static class Books { - public const string GET_BOOKS_LITE = "books/lite"; - public const string GET_BOOK = "books/{id}"; - public const string UPDATE_BOOK = "books/{id}"; - public const string UPDATE_BOOK_COVER = "books/{id}/cover"; - public const string GET_BOOK_READING_MANIFEST = "books/{bookId}/reading/manifest"; - public const string GET_BOOK_READING_AVAILABILITY = "books/{bookId}/reading/availability"; - public const string GET_BOOK_READING_SECTION = "books/{bookId}/reading/sections/{locationRef}"; - public const string GET_BOOK_READING_RESOURCE = "books/{bookId}/reading/resources/{resourceKey}"; + public const string GET_BOOKS_LITE = "libraries/{libraryId}/books/lite"; + public const string GET_BOOK = "libraries/{libraryId}/books/{bookId}"; + public const string UPDATE_BOOK = "libraries/{libraryId}/books/{bookId}"; + public const string UPDATE_BOOK_COVER = "libraries/{libraryId}/books/{bookId}/cover"; + public const string GET_BOOK_READING_MANIFEST = "libraries/{libraryId}/books/{bookId}/reading/manifest"; + public const string GET_BOOK_READING_AVAILABILITY = "libraries/{libraryId}/books/{bookId}/reading/availability"; + public const string GET_BOOK_READING_SECTION = "libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef}"; + public const string GET_BOOK_READING_RESOURCE = "libraries/{libraryId}/books/{bookId}/reading/resources/{resourceKey}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs index 1eed9199..ba998f99 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Books.cs @@ -12,10 +12,10 @@ public static partial class WebRoutes { public const string INDEX = "{culture}/library/written-content-library/books-library/books"; public const string GET_LIBRARY_ITEMS = "{culture}/library/written-content-library/books-library/books/api-get-library-items"; - public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{id}"; - public const string GET_BOOK_DETAILS = "{culture}/library/written-content-library/books-library/books/{id}/api-get-book"; - public const string SAVE_BOOK = "{culture}/library/written-content-library/books-library/books/{id}/api-save-book"; - public const string UPDATE_BOOK_COVER = "{culture}/library/written-content-library/books-library/books/{id}/api-update-cover"; + public const string EDIT_BOOK = "{culture}/library/written-content-library/books-library/books/{bookId}"; + public const string GET_BOOK_DETAILS = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-book"; + public const string SAVE_BOOK = "{culture}/library/written-content-library/books-library/books/{bookId}/api-save-book"; + public const string UPDATE_BOOK_COVER = "{culture}/library/written-content-library/books-library/books/{bookId}/api-update-cover"; public const string READ = "{culture}/library/written-content-library/books-library/books/{bookId}/read"; public const string GET_READING_MANIFEST = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"; public const string GET_READING_AVAILABILITY = "{culture}/library/written-content-library/books-library/books/{bookId}/api-get-reading-availability"; diff --git a/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs index 4ec993a2..f34d78df 100644 --- a/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs +++ b/src/Lumina.Presentation.Web/Common/Services/CachedThemeHandler.cs @@ -21,9 +21,9 @@ public class CachedThemeHandler : DelegatingHandler { private const string THEMES_SEGMENT = "/api/v1/themes"; private const string THEME_CACHE_TAG = "themes"; - // responses above this size are never kept in the cache, so large binary assets do not bloat the memory + // Responses above this size are never kept in the cache, so large binary assets do not bloat the memory. private const int MAX_CACHEABLE_BYTES = 512 * 1024; - // themes only change when the user switches, reinstalls or deletes them, so the cached responses stay valid for a long time + // Themes only change when the user switches, reinstalls or deletes them, so the cached responses stay valid for a long time. private static readonly TimeSpan s_cacheExpiration = TimeSpan.FromMinutes(30); private readonly HybridCache _hybridCache; @@ -56,7 +56,7 @@ public class CachedThemeHandler : DelegatingHandler if (!requestPath.StartsWith(THEMES_SEGMENT, StringComparison.OrdinalIgnoreCase)) return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); - // a theme mutation replaces the theme files or the active selection, so every cached theme response becomes stale + // A theme mutation replaces the theme files or the active selection, so every cached theme response becomes stale. if (!request.Method.Equals(HttpMethod.Get)) { HttpResponseMessage mutationResponse = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); @@ -65,16 +65,16 @@ public class CachedThemeHandler : DelegatingHandler return mutationResponse; } - // the current user can switch off the theme cache from the settings page, so their requests always receive the freshly edited theme files + // The current user can switch off the theme cache from the settings page, so their requests always receive the freshly edited theme files. Guid? userId = GetCurrentUserId(); if (userId is not null) { - bool isCachingEnabledForUser = await _themeCachePreferenceService.GetAsync(userId.Value, defaultValue: true, cancellationToken).ConfigureAwait(false); + bool isCachingEnabledForUser = await _themeCachePreferenceService.GetAsync(userId.Value, isCachingEnabledByDefault: true, cancellationToken).ConfigureAwait(false); if (!isCachingEnabledForUser) return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } - // key the cached responses by the full request path and query, since each theme endpoint identifies a distinct resource + // Key the cached responses by the full request path and query, since each theme endpoint identifies a distinct resource. string cacheKey = $"themes:{request.RequestUri.PathAndQuery}"; CachedResponse cached = await _hybridCache.GetOrCreateAsync( cacheKey, @@ -96,7 +96,7 @@ public class CachedThemeHandler : DelegatingHandler [THEME_CACHE_TAG], cancellationToken); - // failed responses are only served from the call that produced them, so a temporary failure can never be served from a stale entry + // Failed responses are only served from the call that produced them, so a temporary failure can never be served from a stale entry. if (!IsSuccessful(cached.StatusCode) || cached.Bytes.Length > MAX_CACHEABLE_BYTES) await _hybridCache.RemoveAsync(cacheKey, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs index d6990cdb..d9bd7653 100644 --- a/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/ThemeCachePreferenceService.cs @@ -31,20 +31,20 @@ public class ThemeCachePreferenceService /// Gets whether the theme cache is enabled for the user identified by . /// /// The unique identifier of the user whose preference is read. - /// The value used when the user did not express a preference yet. + /// The value used when the user did not express a preference yet. /// Cancellation token that can be used to stop the execution. /// when the theme cache is enabled for the user, otherwise. - public async Task GetAsync(Guid userId, bool defaultValue, CancellationToken cancellationToken = default) + public async Task GetAsync(Guid userId, bool isCachingEnabledByDefault, CancellationToken cancellationToken = default) { bool? preference = await _hybridCache.GetOrCreateAsync( BuildKey(userId), - (cancellationToken) => new ValueTask(defaultValue), + (cancellationToken) => new ValueTask(isCachingEnabledByDefault), new HybridCacheEntryOptions() { Expiration = s_preferenceLifetime }, cancellationToken: cancellationToken).ConfigureAwait(false); - return preference ?? defaultValue; + return preference ?? isCachingEnabledByDefault; } /// @@ -56,7 +56,7 @@ public class ThemeCachePreferenceService /// An awaitable task representing the asynchronous operation. public async Task SetAsync(Guid userId, bool isEnabled, CancellationToken cancellationToken = default) { - // the value is stored as a nullable bool, matching the read type, since HybridCache keys entries by their stored type + // The value is stored as a nullable bool, matching the read type, since HybridCache keys entries by their stored type. await _hybridCache.SetAsync(BuildKey(userId), (bool?)isEnabled, new HybridCacheEntryOptions() { Expiration = s_preferenceLifetime diff --git a/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs b/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs index 5ee5d892..79595a26 100644 --- a/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs +++ b/src/Lumina.Presentation.Web/Common/Validation/ValidationRule.cs @@ -32,7 +32,7 @@ internal sealed class ValidationRule : IValidationRule? _childValidator; @@ -56,7 +56,7 @@ internal sealed class ValidationRule : IValidationRule : IValidationRule : IValidationRule 0) + if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0) _instanceAwarePredicateErrors[^1] = validationError; - else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + else if (!isLastAddedPredicateInstanceAware && _predicateErrors.Count > 0) _predicateErrors[^1] = validationError; return this; } diff --git a/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs b/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs index 22822f7c..58b4d427 100644 --- a/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs +++ b/src/Lumina.Presentation.Web/Common/Validation/ValidationRuleForEach.cs @@ -20,7 +20,7 @@ internal sealed class ValidationRuleForEach : IValidationRule _instanceAwarePredicateErrors = []; private Error currentError = Error.Validation(); private Func? condition; - private bool lastAddedPredicateIsInstanceAware; + private bool isLastAddedPredicateInstanceAware; private AbstractValidator? _childValidator; /// @@ -41,7 +41,7 @@ internal sealed class ValidationRuleForEach : IValidationRule : IValidationRule : IValidationRuleThe current instance for method chaining. public IRuleBuilder WithError(Error error) { - // validation rules always produce validation errors, regardless of the error type of the source error + // Validation rules always produce validation errors, regardless of the error type of the source error. Error validationError = Error.Validation(description: error.Description); currentError = validationError; - if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0) + if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0) _instanceAwarePredicateErrors[^1] = validationError; - else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0) + else if (!isLastAddedPredicateInstanceAware && _predicateErrors.Count > 0) _predicateErrors[^1] = validationError; return this; } @@ -106,7 +106,7 @@ internal sealed class ValidationRuleForEach : IValidationRuleOne per failing predicate, per item; empty if every item passes. public IEnumerable Validate(TRequest instance) { - // evaluate the condition first, if it returns false, skip validation entirely. + // Evaluate the condition first, if it returns false, skip validation entirely.. if (condition is not null && !condition(instance)) yield break; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs index 4ef4680a..af667caf 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpoint.cs @@ -49,7 +49,7 @@ public class GetDirectoriesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken) { - DirectoryDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + DirectoryDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&shouldIncludeHiddenElements={request.ShouldIncludeHiddenElements}", cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs index 39adb453..65e9840e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointSummary.cs @@ -24,11 +24,11 @@ public class GetDirectoriesEndpointSummary : Summary r.Path, "The file system path for which to get the directories. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); ExampleRequest = new GetDirectoriesRequest( Path: "/media/movies/", - IncludeHiddenElements: true + ShouldIncludeHiddenElements: true ); Response(200, "The directories of the file system path are returned.", example: new SuccessResponse(true, default)); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs index 3339abf9..14dfc99f 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpoint.cs @@ -49,7 +49,7 @@ public class GetFilesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken) { - FileDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Files.GET_FILES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + FileDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Files.GET_FILES}?path={Uri.EscapeDataString(request.Path!)}&shouldIncludeHiddenElements={request.ShouldIncludeHiddenElements}", cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs index db6da811..6b3d32e1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointSummary.cs @@ -24,11 +24,11 @@ public class GetFilesEndpointSummary : Summary r.Path, "The file system path for which to get the files. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); ExampleRequest = new GetFilesRequest( Path: "/media/movies/", - IncludeHiddenElements: true + ShouldIncludeHiddenElements: true ); Response(200, "The files of the file system path are returned.", example: new SuccessResponse(true, default)); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs index 983877ef..d70901d3 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpoint.cs @@ -49,7 +49,7 @@ public class GetTreeFilesEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken) { - FileSystemTreeNodeDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Files.GET_TREE_FILES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + FileSystemTreeNodeDto[] response = await _apiHttpClient.GetAsync($"{ApiRoutes.Files.GET_TREE_FILES}?path={Uri.EscapeDataString(request.Path!)}&shouldIncludeHiddenElements={request.ShouldIncludeHiddenElements}", cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs index abe588aa..5973ab9b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointSummary.cs @@ -24,11 +24,11 @@ public class GetTreeFilesEndpointSummary : Summary r.Path, "The file system path for which to get the tree files. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden file system elements or not. Optional."); ExampleRequest = new GetTreeFilesRequest( Path: "/media/movies/", - IncludeHiddenElements: true + ShouldIncludeHiddenElements: true ); Response(200, "The file system tree of the file system path is returned.", example: new SuccessResponse(true, default)); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs index db41a478..1f958c6f 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpoint.cs @@ -49,7 +49,7 @@ public class CheckPathExistsEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken) { - PathExistsDto response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.CHECK_PATH_EXISTS}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements={request.IncludeHiddenElements}", cancellationToken).ConfigureAwait(false); + PathExistsDto response = await _apiHttpClient.GetAsync($"{ApiRoutes.Path.CHECK_PATH_EXISTS}?path={Uri.EscapeDataString(request.Path!)}&shouldIncludeHiddenElements={request.ShouldIncludeHiddenElements}", cancellationToken).ConfigureAwait(false); return JsonSuccess(new { exists = response.Exists }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs index edb14f0e..1a2549df 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointSummary.cs @@ -22,11 +22,11 @@ public class CheckPathExistsEndpointSummary : Summary r.Path, "The file system path to check the existence of. Required."); - RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not. Optional."); + RequestParam(r => r.ShouldIncludeHiddenElements, "Whether to include hidden elements in the search results, or not. Optional."); ExampleRequest = new CheckPathExistsRequest( Path: "/media/movies/", - IncludeHiddenElements: true + ShouldIncludeHiddenElements: true ); Response(200, "Whether the file system path exists is returned.", example: new { success = true, data = new { exists = true } }); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs index 94a6443b..ec93be44 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointSummary.cs @@ -20,7 +20,7 @@ public class CancelLibraryScanEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose scan is cancelled. Required."); RequestParam(r => r.ScanId, "The Id of the scan to cancel. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs index bc8a86fd..d8a0af87 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointSummary.cs @@ -20,7 +20,7 @@ public class DeleteLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library to delete. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs index 6a7acc2d..c5fe27e1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointSummary.cs @@ -19,7 +19,7 @@ public class EditLibraryViewEndpointSummary : Summary r.Id, "The unique identifier of the media library to edit. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs index 3bc963e8..0b20d2a2 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetArtworkProviders/GetArtworkProvidersEndpointSummary.cs @@ -21,7 +21,7 @@ public class GetArtworkProvidersEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose artwork providers are retrieved. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs index 4673ac07..4ced74bf 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetBookReaders/GetBookReadersEndpointSummary.cs @@ -19,7 +19,7 @@ public class GetBookReadersEndpointSummary : Summary r.LibraryId, "The Id of the media library whose book readers are retrieved. Required."); ExampleRequest = new GetBookReadersRequest( diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs index 4ea5c5d7..505a1901 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointSummary.cs @@ -21,7 +21,7 @@ public class GetMetadataProvidersEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose metadata providers are retrieved. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs index 8614c515..4393cec0 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderArtworkProviders/ReorderArtworkProvidersEndpointSummary.cs @@ -20,7 +20,7 @@ public class ReorderArtworkProvidersEndpointSummary : Summary r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); ExampleRequest = new ReorderLibraryArtworkProvidersRequest diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs index 1e6ff0e6..e226dbe5 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointSummary.cs @@ -21,7 +21,7 @@ public class ReorderMetadataProvidersEndpointSummary : Summary r.LibraryId, "The Id of the media library whose metadata providers are reordered. Required."); RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs index 5d29c1fc..1a09f1a8 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointSummary.cs @@ -21,7 +21,7 @@ public class ScanLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library to scan. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs index a926f9d0..01b8d452 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetArtworkProviderEnabled/SetArtworkProviderEnabledEndpointSummary.cs @@ -20,7 +20,7 @@ public class SetArtworkProviderEnabledEndpointSummary : Summary r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library, or not. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs index b8bd8a76..831c963a 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetBookReaderEnabled/SetBookReaderEnabledEndpointSummary.cs @@ -20,7 +20,7 @@ public class SetBookReaderEnabledEndpointSummary : Summary r.LibraryId, "The Id of the media library whose book reader is enabled or disabled. Required."); RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the book reader. Required."); RequestParam(r => r.IsEnabled, "Whether the book reader should be enabled for the media library, or not. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs index 472df6f1..9edfcb0b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointSummary.cs @@ -20,7 +20,7 @@ public class SetMetadataProviderEnabledEndpointSummary : Summary r.LibraryId, "The Id of the media library whose metadata provider is enabled or disabled. Required."); RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the metadata. Required."); RequestParam(r => r.IsEnabled, "Whether the metadata provider should be enabled for the media library, or not. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs index dc80331c..7e68cfb8 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpoint.cs @@ -23,7 +23,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; /// -/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id} route. +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId} route. /// public class EditBookViewEndpoint : BaseEndpoint { @@ -85,8 +85,8 @@ public class EditBookViewEndpoint : BaseEndpoint // The view needs the full details of the book to show its current values, so they are fetched from the API up front; the route // value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted route value can never escape // its URL segment, and an unparseable id is reported by the API as a missing book id. - request = request with { Id = Guid.TryParse(request.Id, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; - BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id), cancellationToken).ConfigureAwait(false); + request = request with { BookId = Guid.TryParse(request.BookId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; + BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId), cancellationToken).ConfigureAwait(false); string title = book.Metadata?.Title ?? string.Empty; // The themed view is a regular page that submits its own requests, so a fresh anti-forgery token must be issued for it. @@ -104,8 +104,8 @@ public class EditBookViewEndpoint : BaseEndpoint ["bookId"] = book.Id.ToString(), ["libraryId"] = book.LibraryId.ToString(), ["antiforgeryToken"] = antiforgeryTokens.RequestToken, - ["saveUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { id = default(Guid) }) ?? string.Empty, - ["coverUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { id = default(Guid) }) ?? string.Empty, + ["saveUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { bookId = default(Guid) }) ?? string.Empty, + ["coverUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { bookId = default(Guid) }) ?? string.Empty, ["backUrl"] = (_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX) ?? string.Empty) + "?libraryId=" + book.LibraryId, ["bookJson"] = JsonSerializer.Serialize(book, s_camelCaseJsonOptions), ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer), diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs index f00e4870..17dd309d 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointSummary.cs @@ -19,12 +19,14 @@ public class EditBookViewEndpointSummary : Summary r.Id, "The unique identifier of the book to edit. Required."); + RequestParam(r => r.BookId, "The unique identifier of the book to edit. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new GetBookRequest( - Id: Guid.NewGuid().ToString() + BookId: Guid.NewGuid().ToString(), + LibraryId: Guid.NewGuid() ); Response(200, "The view for editing the book is rendered."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs index 34c07891..b4da4465 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpoint.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBookDetails; /// -/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-get-book route. +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-get-book route. /// public class GetBookDetailsEndpoint : BaseEndpoint { @@ -51,9 +51,9 @@ public class GetBookDetailsEndpoint : BaseEndpoint { // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted route value can // never escape its URL segment, and an unparseable id is reported by the API as a missing book id. - request = request with { Id = Guid.TryParse(request.Id, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; + request = request with { BookId = Guid.TryParse(request.BookId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString() }; - BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id), cancellationToken).ConfigureAwait(false); + BookDetailsDto book = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId), cancellationToken).ConfigureAwait(false); return JsonSuccess(book); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs index c8a50e2f..74c7e08e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointSummary.cs @@ -21,12 +21,14 @@ public class GetBookDetailsEndpointSummary : Summary r.Id, "The unique identifier of the book to get. Required."); + RequestParam(r => r.BookId, "The unique identifier of the book to get. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new GetBookRequest( - Id: Guid.NewGuid().ToString() + BookId: Guid.NewGuid().ToString(), + LibraryId: Guid.NewGuid() ); Response(200, "The details of the book are returned.", example: new SuccessResponse(true, default)); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs index e411d87b..ff26b11a 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs @@ -7,6 +7,7 @@ using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; using Microsoft.AspNetCore.Http; using System; +using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -60,21 +61,23 @@ public class GetLibraryItemsEndpoint : BaseEndpointThe API endpoint to which the retrieval request is sent. private static string BuildItemsEndpoint(GetBooksLiteRequest query) { - StringBuilder endpoint = new(ApiRoutes.Books.GET_BOOKS_LITE); - endpoint.Append($"?libraryId={query.LibraryId}"); + StringBuilder endpoint = new(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", query.LibraryId.ToString())); + List parameters = []; if (query.CurrentPage is not null) - endpoint.Append($"¤tPage={query.CurrentPage}"); + parameters.Add($"currentPage={query.CurrentPage}"); if (query.PerPage is not null) - endpoint.Append($"&perPage={query.PerPage}"); + parameters.Add($"perPage={query.PerPage}"); if (!string.IsNullOrWhiteSpace(query.SearchTerm)) - endpoint.Append($"&searchTerm={Uri.EscapeDataString(query.SearchTerm)}"); + parameters.Add($"searchTerm={Uri.EscapeDataString(query.SearchTerm)}"); if (!string.IsNullOrWhiteSpace(query.FilterAlphaKey)) - endpoint.Append($"&filterAlphaKey={Uri.EscapeDataString(query.FilterAlphaKey)}"); - endpoint.Append($"&shouldIgnoreThePrefixForAlphaPicker={query.ShouldIgnoreThePrefixForAlphaPicker}"); + parameters.Add($"filterAlphaKey={Uri.EscapeDataString(query.FilterAlphaKey)}"); + parameters.Add($"shouldIgnoreThePrefixForAlphaPicker={query.ShouldIgnoreThePrefixForAlphaPicker}"); if (!string.IsNullOrWhiteSpace(query.SortBy)) - endpoint.Append($"&sortBy={Uri.EscapeDataString(query.SortBy)}"); + parameters.Add($"sortBy={Uri.EscapeDataString(query.SortBy)}"); if (query.SortOrder is not null) - endpoint.Append($"&sortOrder={query.SortOrder}"); + parameters.Add($"sortOrder={query.SortOrder}"); + if (parameters.Count > 0) + endpoint.Append('?').Append(string.Join('&', parameters)); return endpoint.ToString(); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs index 785fc1b5..b85309ee 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointSummary.cs @@ -22,7 +22,7 @@ public class GetLibraryItemsEndpointSummary : Summary r.LibraryId, "The Id of the media library whose books are retrieved. Required."); RequestParam(r => r.CurrentPage, "The page of results to retrieve. Optional."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 851f1489..f385ddfb 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -87,7 +87,7 @@ public class BooksIndexViewEndpoint : BaseEndpoint ["itemsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS) ?? string.Empty, ["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty, ["readUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) }) ?? string.Empty, - ["detailsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { id = default(Guid) }) ?? string.Empty, + ["detailsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) }) ?? string.Empty, ["availabilityUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) }) ?? string.Empty, ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs index a7dd2636..1b5a6de9 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointSummary.cs @@ -19,7 +19,7 @@ public class BooksIndexViewEndpointSummary : Summary r.LibraryId, "The unique identifier of the media library whose books are browsed. Optional."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs index 11655081..73e9c386 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpoint.cs @@ -48,7 +48,7 @@ public class GetReadingAvailabilityEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(GetBookReadingAvailabilityRequest request, CancellationToken cancellationToken) { - ReadingAvailabilityDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), cancellationToken).ConfigureAwait(false); + ReadingAvailabilityDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), cancellationToken).ConfigureAwait(false); return Results.Json(new { success = response.IsAvailable, errorCode = response.ErrorCode, libraryId = response.LibraryId }); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs index 97322053..aa3564cd 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointSummary.cs @@ -21,9 +21,11 @@ public class GetReadingAvailabilityEndpointSummary : Summary r.BookId, "The Id of the book whose reading availability is checked. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new GetBookReadingAvailabilityRequest( - BookId: Guid.NewGuid() + BookId: Guid.NewGuid(), + LibraryId: Guid.NewGuid() ); Response(200, "The reading availability of the book is returned.", diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs index 7f154d9e..5bf50927 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpoint.cs @@ -52,7 +52,7 @@ public class GetReadingManifestEndpoint : BaseEndpoint(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), cancellationToken).ConfigureAwait(false); + ReadingManifestDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); } catch (ApiException apiException) diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs index 9a853dae..341f0c13 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointSummary.cs @@ -21,9 +21,11 @@ public class GetReadingManifestEndpointSummary : Summary r.BookId, "The Id of the book whose reading manifest is retrieved. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new GetBookReadingManifestRequest( - BookId: Guid.NewGuid() + BookId: Guid.NewGuid(), + LibraryId: Guid.NewGuid() ); Response(200, "The reading manifest of the book is returned."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs index 1ff7295e..1c4a5e25 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpoint.cs @@ -50,6 +50,7 @@ public class GetReadingResourceEndpoint : BaseEndpoint ExecuteAsync(GetBookReadingResourceRequest request, CancellationToken cancellationToken) { BlobDataDto response = await _apiHttpClient.GetBlobAsync(ApiRoutes.Books.GET_BOOK_READING_RESOURCE + .Replace("{libraryId}", request.LibraryId.ToString()) .Replace("{bookId}", request.BookId.ToString()) .Replace("{resourceKey}", Uri.EscapeDataString(request.ResourceKey)), cancellationToken).ConfigureAwait(false); // The resource is served without content sniffing, so that the browser never renders book content as anything but the media type the API declared. diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs index b541cc66..9beb11e7 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointSummary.cs @@ -22,10 +22,12 @@ public class GetReadingResourceEndpointSummary : Summary r.BookId, "The Id of the book whose resource is retrieved. Required."); RequestParam(r => r.ResourceKey, "The opaque resource key of the resource. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new GetBookReadingResourceRequest( BookId: Guid.NewGuid(), - ResourceKey: "cover-image" + ResourceKey: "cover-image", + LibraryId: Guid.NewGuid() ); Response(200, "The resource of the book is returned."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs index 705a20a4..0bdb3f4c 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpoint.cs @@ -50,6 +50,7 @@ public class GetReadingSectionEndpoint : BaseEndpoint ExecuteAsync(GetBookReadingSectionRequest request, CancellationToken cancellationToken) { ReadingSectionDto response = await _apiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_SECTION + .Replace("{libraryId}", request.LibraryId.ToString()) .Replace("{bookId}", request.BookId.ToString()) .Replace("{locationRef}", Uri.EscapeDataString(request.LocationRef)), cancellationToken).ConfigureAwait(false); return JsonSuccess(response); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs index 293f49dc..0b3778a1 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointSummary.cs @@ -22,10 +22,12 @@ public class GetReadingSectionEndpointSummary : Summary r.BookId, "The Id of the book whose reading section is retrieved. Required."); RequestParam(r => r.LocationRef, "The opaque location reference of the reading section. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new GetBookReadingSectionRequest( BookId: Guid.NewGuid(), - LocationRef: "chapter-1" + LocationRef: "chapter-1", + LibraryId: Guid.NewGuid() ); Response(200, "The content of the reading section is returned."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs index 1cc75348..1df4977f 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/Read/ReadViewEndpointSummary.cs @@ -19,11 +19,13 @@ public class ReadViewEndpointSummary : Summary r.BookId, "The Id of the book to read. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); ExampleRequest = new ReadBookViewRequest( - BookId: Guid.NewGuid() + BookId: Guid.NewGuid(), + LibraryId: Guid.NewGuid() ); Response(200, "The reading view of the book is displayed."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs index e51e1720..469a89e2 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook; /// -/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-save-book route. +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-save-book route. /// public class SaveBookEndpoint : BaseEndpoint { @@ -50,14 +50,14 @@ public class SaveBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) { - // The book is identified by the {id} route value, not by the id posted in the form, so that a mismatched id can never redirect + // The book is identified by the {bookId} route value, not by the id posted in the form, so that a mismatched id can never redirect // the update to another book; the value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted // route value can never escape its URL segment, and an unparseable id is reported by the API as a missing book id. - string routeId = HttpContext.Request.RouteValues["id"]?.ToString() ?? string.Empty; - request.Id = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString(); + string routeId = HttpContext.Request.RouteValues["bookId"]?.ToString() ?? string.Empty; + request.BookId = Guid.TryParse(routeId, out Guid bookId) ? bookId.ToString() : Guid.Empty.ToString(); BookDetailsDto book = await _apiHttpClient.PutAsync( - ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", request.Id), request, cancellationToken).ConfigureAwait(false); + ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId), request, cancellationToken).ConfigureAwait(false); return JsonSuccess(book); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs index a5fe6ee9..5ecaadfa 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs @@ -1,10 +1,11 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.DTO.MediaContributors; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary; using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Common.Enums.BookLibrary; +using Lumina.Presentation.Web.Common.Enums.MediaContributors; using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Enums.Common; using System; @@ -26,9 +27,10 @@ public class SaveBookEndpointSummary : Summary r.Id, "The unique identifier of the book to update. Required."); + RequestParam(r => r.BookId, "The unique identifier of the book to update. Required."); + RequestParam(r => r.LibraryId, "The Id of the media library the book belongs to. Required."); RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); RequestParam(r => r.Metadata!.OriginalTitle, "The original title of the book, if different from the current title. Optional."); @@ -72,7 +74,8 @@ public class SaveBookEndpointSummary : Summary -/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{id}/api-update-cover route. +/// API endpoint for the /{culture}/library/written-content-library/books-library/books/{bookId}/api-update-cover route. /// public class UpdateBookCoverEndpoint : BaseEndpoint { @@ -50,19 +51,38 @@ public class UpdateBookCoverEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - // The endpoint takes no typed request, because its body is a multipart file, so the book id is read from the {id} route - // value; an unparseable value becomes Guid.Empty, which the upstream API reports as a missing book id. - Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["id"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty; + // The endpoint takes no typed request, because its body is a multipart file, so the book id is read from the {bookId} route + // value and the owning library from the {libraryId} query string; an unparseable book id becomes Guid.Empty. A missing file + // is forwarded as a multipart form without any file, so that the upstream API reports it with its own validation error. + Guid bookId = Guid.TryParse(HttpContext.Request.RouteValues["bookId"]?.ToString(), out Guid parsedBookId) ? parsedBookId : Guid.Empty; + string? libraryId = HttpContext.Request.Query["libraryId"].ToString(); - // The cover is the first file of the multipart form, and without it the request cannot update anything. - IFormFile? cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; - if (cover is null) - return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The uploaded cover image is missing."); + // The cover is the first file of the multipart form; a non-multipart body, or a multipart body without any file, is treated + // as a missing cover and forwarded as a request without a file, so that the upstream API reports it with its own validation error. + IFormFile? cover = null; + if (HttpContext.Request.HasFormContentType) + { + try + { + cover = HttpContext.Request.Form.Files.Count > 0 ? HttpContext.Request.Form.Files[0] : null; + } + catch (InvalidDataException) + { + cover = null; + } + } // The cover stream must stay open while the file is streamed to the API, and is disposed when the request completes. - await using Stream coverStream = cover.OpenReadStream(); - string? coverPath = await _apiHttpClient.PutMultipartAsync( - ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString()), coverStream, cover.FileName, "cover", cancellationToken).ConfigureAwait(false); - return JsonSuccess(coverPath); + Stream? coverStream = cover?.OpenReadStream(); + try + { + UpdateBookCoverDto response = await _apiHttpClient.PutMultipartAsync( + ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", libraryId).Replace("{bookId}", bookId.ToString()), coverStream, cover?.FileName, "cover", cancellationToken).ConfigureAwait(false); + return JsonSuccess(response.CoverPath); + } + finally + { + coverStream?.Dispose(); + } } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs index d86133f0..df106826 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointSummary.cs @@ -18,7 +18,7 @@ public class UpdateBookCoverEndpointSummary : Summary(true, default)); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs index 7c1d0e0d..69791601 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/UsersManagement/Authentication/GetApiAccessToken/GetApiAccessTokenEndpoint.cs @@ -42,7 +42,7 @@ public class GetApiAccessTokenEndpoint : BaseEndpoint return Task.FromResult(Results.Problem( statusCode: StatusCodes.Status401Unauthorized, title: "Unauthorized", - detail: "You are not authorized")); + detail: "Authentication failed")); string? token = User.FindFirst("Token")?.Value; if (string.IsNullOrEmpty(token)) diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx index d97d0d13..ac29e5d3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ar-SA.resx @@ -141,9 +141,27 @@ يجب أن يكون معدل البت رقمًا موجبًا! + + حدث خطأ غير متوقع أثناء معالجة الطلب! + + + خطأ داخلي في الخادم! + + + قيمة مكررة تنتهك قيد التفرد! + الكتاب موجود بالفعل! + + لا يمكن أن يكون غلاف الكتاب فارغًا! + + + لم يتم العثور على ملف الكتاب! + + + لا يمكن أن يكون معرّف الكتاب فارغًا! + لا يمكن أن تكون مكتبة الكتب فارغة! @@ -153,6 +171,12 @@ لا يمكن أن يكون مسار الكتاب فارغًا! + + يجب ألا يتجاوز مسار الكتاب 2048 حرفًا! + + + يجب أن يكون مسار الكتاب داخل أحد مواقع محتوى المكتبة! + لا يمكن التنقل إلى مستوى أعلى! @@ -273,6 +297,9 @@ خطأ في نقل الملف! + + لا يمكن أن يكون اسم الملف فارغًا! + لم يتم العثور على الملف! @@ -324,9 +351,6 @@ تنسيق ISBN13 غير صالح! - - رمز ISO غير صالح! - تنسيق LCCN غير صالح! @@ -423,6 +447,12 @@ لا يمكن أن يكون نوع المكتبة فارغًا! + + لا يمكن أن يكون معرّف المساهم الإعلامي فارغًا! + + + لم يتم العثور على المساهم الإعلامي! + لا يمكن أن يكون دليل مكتبات الوسائط فارغًا! @@ -732,6 +762,9 @@ لا يمكن أن يكون اسم ملف المكوّن الإضافي فارغاً! + + دور المساهم الإعلامي غير معروف! + نوع ملف المكوّن الإضافي المرفوع غير مدعوم! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index 8f3f3fb6..c8647bcc 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -141,9 +141,27 @@ Bitrate muss eine positive Zahl sein! + + Beim Verarbeiten der Anforderung ist ein unerwarteter Fehler aufgetreten! + + + Interner Serverfehler! + + + Ein doppelter Wert verletzt eine Eindeutigkeitsbedingung! + Buch existiert bereits! + + Das Buchcover darf nicht null sein! + + + Die Buchdatei wurde nicht gefunden! + + + Die Buch-Id darf nicht leer sein! + Die Buchbibliothek darf nicht null sein! @@ -153,6 +171,12 @@ Der Buchpfad darf nicht leer sein! + + Der Buchpfad darf maximal 2048 Zeichen lang sein! + + + Der Buchpfad muss sich in einem der Inhaltsorte der Bibliothek befinden! + Navigation nach oben nicht möglich! @@ -273,6 +297,9 @@ Fehler beim Verschieben der Datei! + + Der Dateiname darf nicht leer sein! + Datei nicht gefunden! @@ -324,9 +351,6 @@ Ungültiges ISBN13-Format! - - Ungültiger ISO-Code! - Ungültiges LCCN-Format! @@ -423,6 +447,12 @@ Bibliothekstyp darf nicht null sein! + + Die Medienbeitragenden-Id darf nicht leer sein! + + + Der Medienbeitragende wurde nicht gefunden! + Das Medienbibliotheksverzeichnis darf nicht leer sein! @@ -732,6 +762,9 @@ Der Dateiname des Plugins darf nicht leer sein! + + Unbekannte Medienbeitragenden-Rolle! + Der Dateityp des hochgeladenen Plugins wird nicht unterstützt! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index 326d2996..f13e7548 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -141,9 +141,27 @@ Bitrate must be a positive number! + + An unexpected error occurred while processing the request! + + + Internal server error! + + + A duplicate value violates a unique constraint! + Book already exists! + + The book cover cannot be null! + + + The book file was not found! + + + The book Id cannot be empty! + The book library cannot be null! @@ -153,6 +171,12 @@ The book path cannot be empty! + + The book path must be maximum 2048 characters long! + + + The book path must be inside one of the library content locations! + Cannot navigate up! @@ -273,6 +297,9 @@ Error moving the file! + + File name cannot be empty! + File not found! @@ -324,9 +351,6 @@ Invalid ISBN13 format! - - Invalid ISO code! - Invalid LCCN format! @@ -423,6 +447,12 @@ Library type cannot be null! + + The media contributor Id cannot be empty! + + + The media contributor was not found! + The media libraries directory cannot be empty! @@ -732,6 +762,9 @@ The plugin file name cannot be empty! + + Unknown media contributor role! + The uploaded plugin file type is not supported! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index a6e0c2e8..faafc50f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -141,9 +141,27 @@ ¡La tasa de bits debe ser un número positivo! + + ¡Se produjo un error inesperado al procesar la solicitud! + + + ¡Error interno del servidor! + + + ¡Un valor duplicado infringe una restricción de unicidad! + ¡El libro ya existe! + + ¡La portada del libro no puede ser nula! + + + ¡No se encontró el archivo del libro! + + + ¡El Id del libro no puede estar vacío! + ¡La biblioteca de libros no puede ser nula! @@ -153,6 +171,12 @@ ¡La ruta del libro no puede estar vacía! + + ¡La ruta del libro debe tener como máximo 2048 caracteres! + + + ¡La ruta del libro debe estar dentro de una de las ubicaciones de contenido de la biblioteca! + ¡No se puede navegar hacia arriba! @@ -273,6 +297,9 @@ ¡Error al mover el archivo! + + ¡El nombre del archivo no puede estar vacío! + ¡Archivo no encontrado! @@ -324,9 +351,6 @@ ¡Formato ISBN13 inválido! - - ¡Código ISO inválido! - ¡Formato LCCN inválido! @@ -423,6 +447,12 @@ ¡El tipo de biblioteca no puede ser nulo! + + ¡El Id del colaborador de medios no puede estar vacío! + + + ¡No se encontró el colaborador de medios! + ¡El directorio de bibliotecas multimedia no puede estar vacío! @@ -732,6 +762,9 @@ El nombre del archivo del plugin no puede estar vacío! + + ¡Rol de colaborador de medios desconocido! + El tipo de archivo del plugin subido no es compatible! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 734e8420..1d433f85 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -141,9 +141,27 @@ Le débit doit être un nombre positif ! + + Une erreur inattendue s'est produite lors du traitement de la requête ! + + + Erreur interne du serveur ! + + + Une valeur en double enfreint une contrainte d'unicité ! + Le livre existe déjà ! + + La couverture du livre ne peut pas être nulle ! + + + Le fichier du livre est introuvable ! + + + L'Id du livre ne peut pas être vide ! + La bibliothèque de livres ne peut pas être nulle ! @@ -153,6 +171,12 @@ Le chemin du livre ne peut pas être vide ! + + Le chemin du livre doit comporter au maximum 2048 caractères ! + + + Le chemin du livre doit se trouver dans l'un des emplacements de contenu de la bibliothèque ! + Impossible de remonter le dossier ! @@ -273,6 +297,9 @@ Erreur lors du déplacement du fichier! + + Le nom du fichier ne peut pas être vide ! + Fichier introuvable! @@ -324,9 +351,6 @@ Format ISBN13 invalide ! - - Code ISO invalide ! - Format LCCN invalide ! @@ -423,6 +447,12 @@ Le type de bibliothèque ne peut pas être nul ! + + L'Id du contributeur multimédia ne peut pas être vide ! + + + Le contributeur multimédia est introuvable ! + Le répertoire des bibliothèques multimédias ne peut pas être vide ! @@ -732,6 +762,9 @@ Le nom du fichier du plugin ne peut pas etre vide ! + + Rôle de contributeur multimédia inconnu ! + Le type de fichier du plugin téléversé n est pas pris en charge ! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index d29f703f..e41878ca 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -141,9 +141,27 @@ Il bitrate deve essere un numero positivo! + + Si è verificato un errore imprevisto durante l'elaborazione della richiesta! + + + Errore interno del server! + + + Un valore duplicato viola un vincolo di unicità! + Il libro esiste già! + + La copertina del libro non può essere nulla! + + + Il file del libro non è stato trovato! + + + L'Id del libro non può essere vuoto! + La libreria dei libri non può essere nulla! @@ -153,6 +171,12 @@ Il percorso del libro non può essere vuoto! + + Il percorso del libro deve essere lungo al massimo 2048 caratteri! + + + Il percorso del libro deve trovarsi in una delle posizioni dei contenuti della libreria! + Impossibile navigare verso l'alto! @@ -273,6 +297,9 @@ Errore durante lo spostamento del file! + + Il nome del file non può essere vuoto! + File non trovato! @@ -324,9 +351,6 @@ Formato ISBN13 non valido! - - Codice ISO non valido! - Formato LCCN non valido! @@ -423,6 +447,12 @@ Il tipo di libreria non può essere nullo! + + L'Id del collaboratore multimediale non può essere vuoto! + + + Il collaboratore multimediale non è stato trovato! + La directory delle librerie multimediali non può essere vuota! @@ -732,6 +762,9 @@ Il nome del file del plugin non può essere vuoto! + + Ruolo del collaboratore multimediale sconosciuto! + Il tipo di file del plugin caricato non è supportato! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 811c5865..2cd57da7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -141,9 +141,27 @@ ビットレートは正の数でなければなりません! + + リクエストの処理中に予期しないエラーが発生しました! + + + サーバー内部エラー! + + + 重複した値が一意制約に違反しています! + 本はすでに存在します! + + 本の表紙は null にできません。 + + + 本のファイルが見つかりませんでした。 + + + 本の Id は空にできません。 + 本のライブラリを null にすることはできません。 @@ -153,6 +171,12 @@ 本のパスを空にすることはできません。 + + 本のパスは最大 2048 文字です。 + + + 本のパスはライブラリのコンテンツの場所のいずれかにある必要があります! + 上の階層に移動できません! @@ -273,6 +297,9 @@ ファイルの移動に失敗しました! + + ファイル名を空にすることはできません! + ファイルが見つかりません! @@ -324,9 +351,6 @@ 無効なISBN13形式です! - - 無効なISOコードです! - 無効なLCCN形式です! @@ -423,6 +447,12 @@ ライブラリタイプをnullにすることはできません! + + メディア寄稿者の Id は空にできません。 + + + メディア寄稿者が見つかりませんでした! + メディアライブラリのディレクトリを空にすることはできません。 @@ -732,6 +762,9 @@ プラグインのファイル名を空にすることはできません! + + 不明なメディア寄稿者の役割です。 + アップロードされたプラグインのファイルタイプはサポートされていません! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 7dc35049..fe193be8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -141,9 +141,27 @@ Bitrate must be a positive number! + + An unexpected error occurred while processing the request! + + + Internal server error! + + + A duplicate value violates a unique constraint! + Book already exists! + + The book cover cannot be null! + + + The book file was not found! + + + The book Id cannot be empty! + The book library cannot be null! @@ -153,6 +171,12 @@ The book path cannot be empty! + + The book path must be maximum 2048 characters long! + + + The book path must be inside one of the library content locations! + Cannot navigate up! @@ -273,6 +297,9 @@ Error moving the file! + + File name cannot be empty! + File not found! @@ -324,9 +351,6 @@ Invalid ISBN13 format! - - Invalid ISO code! - Invalid LCCN format! @@ -423,6 +447,12 @@ Library type cannot be null! + + The media contributor Id cannot be empty! + + + The media contributor was not found! + The media libraries directory cannot be empty! @@ -732,6 +762,9 @@ The plugin file name cannot be empty! + + Unknown media contributor role! + The uploaded plugin file type is not supported! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index c4dd1bc3..2aa1c5dd 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -141,9 +141,27 @@ Rata de biți trebuie să fie un număr pozitiv! + + A apărut o eroare neașteptată în timpul procesării cererii! + + + Eroare internă de server! + + + O valoare duplicată încalcă o constrângere de unicitate! + Cartea există deja! + + Coperta cărții nu poate fi nulă! + + + Fișierul cărții nu a fost găsit! + + + Id-ul cărții nu poate fi gol! + Biblioteca de carti nu poate fi nula! @@ -153,6 +171,12 @@ Calea cartii nu poate fi goala! + + Calea cărții trebuie să aibă maximum 2048 de caractere! + + + Calea cărții trebuie să fie în una dintre locațiile de conținut ale bibliotecii! + Nu se poate naviga în sus! @@ -273,6 +297,9 @@ Eroare la mutarea fișierului! + + Numele fișierului nu poate fi gol! + Fișierul nu a fost găsit! @@ -324,9 +351,6 @@ Format ISBN13 invalid! - - Cod ISO invalid! - Format LCCN invalid! @@ -423,6 +447,12 @@ Tipul bibliotecii nu poate fi nul! + + Id-ul contribuitorului media nu poate fi gol! + + + Contribuitorul media nu a fost găsit! + Directorul bibliotecilor media nu poate fi gol! @@ -732,6 +762,9 @@ Numele fișierului pluginului nu poate fi gol! + + Rol de contribuitor media necunoscut! + Tipul de fișier al pluginului încărcat nu este acceptat! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx index 20b6d57d..ea2e4393 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.uk-UA.resx @@ -141,9 +141,27 @@ Бітрейт має бути додатним числом! + + Під час обробки запиту сталася неочікувана помилка! + + + Внутрішня помилка сервера! + + + Дублікат значення порушує обмеження унікальності! + Книга вже існує! + + Обкладинка книги не може бути null! + + + Файл книги не знайдено! + + + Ідентифікатор книги не може бути порожнім! + Бібліотека книг не може бути порожньою! @@ -153,6 +171,12 @@ Шлях до книги не може бути порожнім! + + Шлях до книги має містити щонайбільше 2048 символів! + + + Шлях книги має знаходитися в одному з розташувань вмісту бібліотеки! + Неможливо перейти на рівень вище! @@ -273,6 +297,9 @@ Помилка переміщення файлу! + + Ім'я файлу не може бути порожнім! + Файл не знайдено! @@ -324,9 +351,6 @@ Недійсний формат ISBN13! - - Недійсний ISO-код! - Недійсний формат LCCN! @@ -423,6 +447,12 @@ Тип бібліотеки не може бути порожнім! + + Ідентифікатор медіаспівавтора не може бути порожнім! + + + Медіа-учасника не знайдено! + Каталог медіатек не може бути порожнім! @@ -732,6 +762,9 @@ Ім'я файлу плагіна не може бути порожнім! + + Невідома роль медіаспівавтора! + Тип файлу завантаженого плагіна не підтримується! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index 818ffca4..0b05709e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -141,9 +141,27 @@ 比特率必须是正数! + + 处理请求时发生意外错误! + + + 服务器内部错误! + + + 重复的值违反了唯一约束! + 图书已存在! + + 书籍封面不能为 null! + + + 未找到书籍文件! + + + 书籍 Id 不能为空! + 图书库不能为 null! @@ -153,6 +171,12 @@ 图书路径不能为空! + + 书籍路径长度最多为 2048 个字符! + + + 书籍路径必须位于媒体库内容位置之一内! + 无法向上导航! @@ -273,6 +297,9 @@ 移动文件时出错! + + 文件名不能为空! + 找不到文件! @@ -324,9 +351,6 @@ 无效的ISBN13格式! - - 无效的ISO代码! - 无效的LCCN格式! @@ -423,6 +447,12 @@ 库类型不能为空! + + 媒体贡献者 Id 不能为空! + + + 未找到媒体贡献者! + 媒体库目录不能为空! @@ -732,6 +762,9 @@ 插件文件名不能为空! + + 未知的媒体贡献者角色! + 不支持上传的插件文件类型! diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx index aa6e2aec..61785310 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ar-SA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ زيمبابوي + + الدور + + + ممثل + + + مخرج + + + كاتب سيناريو + + + ملحن + + + كاتب كلمات + + + موزع موسيقي + + + قائد أوركسترا + + + منتج + + + منتج تنفيذي + + + مهندس صوت + + + مهندس مكساج + + + ريمكس + + + شركة إنتاج + + + غناء + + + غناء مساند + + + غيتار + + + غيتار باس + + + طبول + + + إيقاع + + + آلات مفاتيح + + + بيانو + + + سينثسيزر + + + آلات وترية + + + آلات نفخ خشبية + + + آلات نفخ نحاسية + + + جوقة + + + منسق الأوركسترا + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx index 736bfbd1..6d329eac 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Simbabwe + + Rolle + + + Schauspieler + + + Regisseur + + + Drehbuchautor + + + Komponist + + + Textdichter + + + Arrangeur + + + Dirigent + + + Produzent + + + Executive Producer + + + Toningenieur + + + Tonmischer + + + Remixer + + + Plattenlabel + + + Gesang + + + Begleitgesang + + + Gitarre + + + Bassgitarre + + + Schlagzeug + + + Perkussion + + + Keyboards + + + Klavier + + + Synthesizer + + + Streicher + + + Holzblasinstrumente + + + Blechblasinstrumente + + + Chor + + + Orchestrator + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx index 7ad32787..1c2ea00e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Zimbabwe + + Role + + + Actor + + + Director + + + Screenwriter + + + Composer + + + Lyricist + + + Arranger + + + Conductor + + + Producer + + + Executive producer + + + Engineer + + + Mixer + + + Remixer + + + Record label + + + Vocals + + + Backing vocals + + + Guitar + + + Bass guitar + + + Drums + + + Percussion + + + Keyboards + + + Piano + + + Synthesizer + + + Strings + + + Woodwinds + + + Brass + + + Choir + + + Orchestrator + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx index d8e42082..18483a5a 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Zimbabue + + Rol + + + Actor + + + Director + + + Guionista + + + Compositor + + + Letrista + + + Arreglista + + + Director de orquesta + + + Productor + + + Productor ejecutivo + + + Ingeniero de sonido + + + Mezclador + + + Remezclador + + + Sello discográfico + + + Voz + + + Coros + + + Guitarra + + + Bajo + + + Batería + + + Percusión + + + Teclados + + + Piano + + + Sintetizador + + + Cuerdas + + + Maderas + + + Metales + + + Coro + + + Orquestador + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx index 29f61f5e..996ef9fa 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Zimbabwe + + Rôle + + + Acteur + + + Réalisateur + + + Scénariste + + + Compositeur + + + Parolier + + + Arrangeur + + + Chef d'orchestre + + + Producteur + + + Producteur exécutif + + + Ingénieur du son + + + Mixeur + + + Remixeur + + + Maison de disques + + + Chant + + + Chœurs + + + Guitare + + + Guitare basse + + + Batterie + + + Percussions + + + Claviers + + + Piano + + + Synthétiseur + + + Cordes + + + Bois + + + Cuivres + + + Chœur + + + Orchestrateur + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx index 665c573b..1e8fe8fe 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Zimbabwe + + Ruolo + + + Attore + + + Regista + + + Sceneggiatore + + + Compositore + + + Paroliere + + + Arrangiatore + + + Direttore d'orchestra + + + Produttore + + + Produttore esecutivo + + + Ingegnere del suono + + + Mixer + + + Remixer + + + Etichetta discografica + + + Voce + + + Cori + + + Chitarra + + + Basso + + + Batteria + + + Percussioni + + + Tastiere + + + Pianoforte + + + Sintetizzatore + + + Archi + + + Legni + + + Ottoni + + + Coro + + + Orchestratore + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx index bbe6519c..27d13c76 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ ジンバブエ + + 役割 + + + 俳優 + + + 監督 + + + 脚本家 + + + 作曲家 + + + 作詞家 + + + 編曲家 + + + 指揮者 + + + プロデューサー + + + エグゼクティブプロデューサー + + + エンジニア + + + ミキサー + + + リミキサー + + + レコードレーベル + + + ボーカル + + + バックボーカル + + + ギター + + + ベースギター + + + ドラム + + + パーカッション + + + キーボード + + + ピアノ + + + シンセサイザー + + + 弦楽器 + + + 木管楽器 + + + 金管楽器 + + + 合唱 + + + オーケストレーター + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx index fbdda4b4..55db7171 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -966,4 +966,88 @@ Zimbabwe + + Role + + + Actor + + + Director + + + Screenwriter + + + Composer + + + Lyricist + + + Arranger + + + Conductor + + + Producer + + + Executive producer + + + Engineer + + + Mixer + + + Remixer + + + Record label + + + Vocals + + + Backing vocals + + + Guitar + + + Bass guitar + + + Drums + + + Percussion + + + Keyboards + + + Piano + + + Synthesizer + + + Strings + + + Woodwinds + + + Brass + + + Choir + + + Orchestrator + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx index 3acbe541..557439a8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Zimbabwe + + Rol + + + Actor + + + Regizor + + + Scenarist + + + Compozitor + + + Textier + + + Aranjor + + + Dirijor + + + Producător + + + Producător executiv + + + Inginer de sunet + + + Mixer + + + Remixer + + + Casă de discuri + + + Voce + + + Coruri + + + Chitară + + + Chitară bas + + + Tobe + + + Percuție + + + Claviaturi + + + Pian + + + Sintetizator + + + Coarde + + + Suflat din lemn + + + Alămuri + + + Cor + + + Orchestrator + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx index ef5ae45a..3b61a2ae 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ Зімбабве + + Роль + + + Актор + + + Режисер + + + Сценарист + + + Композитор + + + Автор тексту + + + Аранжувальник + + + Диригент + + + Продюсер + + + Виконавчий продюсер + + + Звукорежисер + + + Мікшувальник + + + Реміксер + + + Лейбл + + + Вокал + + + Бек-вокал + + + Гітара + + + Бас-гітара + + + Барабани + + + Перкусія + + + Клавішні + + + Фортепіано + + + Синтезатор + + + Струнні + + + Дерев'яні духові + + + Мідні духові + + + Хор + + + Оркестратор + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx index 794b2365..81807621 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -967,4 +967,88 @@ 津巴布韦 + + 角色 + + + 演员 + + + 导演 + + + 编剧 + + + 作曲家 + + + 作词人 + + + 编曲人 + + + 指挥家 + + + 制作人 + + + 执行制片人 + + + 录音工程师 + + + 混音师 + + + 混音师 + + + 唱片公司 + + + 主唱 + + + 和声 + + + 吉他 + + + 贝斯 + + + 鼓 + + + 打击乐 + + + 键盘 + + + 钢琴 + + + 合成器 + + + 弦乐 + + + 木管乐 + + + 铜管乐 + + + 合唱团 + + + 配器师 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs index a535de9c..25d516d9 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs @@ -49,7 +49,7 @@ public sealed class ThemeTemplateEngine ThemeSectionNodeDto? scriptsSection = null; foreach (ThemeTemplateNodeDto node in parseResult.Value) { - if (node is ThemeSectionNodeDto { Inverted: false } section + if (node is ThemeSectionNodeDto { IsInverted: false } section && scriptsSection is null && string.Equals(section.Expression, "scripts", StringComparison.OrdinalIgnoreCase)) { @@ -146,7 +146,7 @@ public sealed class ThemeTemplateEngine if (childrenResult.IsFailure) return childrenResult.Errors; - nodes.Add(new ThemeSectionNodeDto(expression, Inverted: tag[0] == '^', Children: childrenResult.Value)); + nodes.Add(new ThemeSectionNodeDto(expression, IsInverted: tag[0] == '^', Children: childrenResult.Value)); break; } case '/': @@ -247,16 +247,16 @@ public sealed class ThemeTemplateEngine private static Result RenderSection(ThemeSectionNodeDto section, ThemeRenderScopeDto scope, StringBuilder output) { object? value = Resolve(section.Expression, scope); - bool truthy = IsTruthy(value); - if (section.Inverted) + bool isTruthy = IsTruthy(value); + if (section.IsInverted) { - if (!truthy) + if (!isTruthy) return RenderNodes(section.Children, scope, output); return Result.Success; } - if (!truthy) + if (!isTruthy) return Result.Success; if (value is bool) @@ -425,7 +425,7 @@ public sealed class ThemeTemplateEngine return value switch { null => string.Empty, - bool boolean => boolean ? "true" : "false", + bool isBoolean => isBoolean ? "true" : "false", DateTime dateTime => dateTime.ToString("O", CultureInfo.InvariantCulture), DateTimeOffset dateTimeOffset => dateTimeOffset.ToString("O", CultureInfo.InvariantCulture), IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty, diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml index 1ade1b2e..5708fa28 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -66,7 +66,7 @@ const libraryId = '@(Model.Id ?? Guid.Empty)'; const readUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.READ, new { bookId = default(Guid) })'; - const detailsUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { id = default(Guid) })'; + const detailsUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) })'; const availabilityUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })'; // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const booksContainer = document.getElementById('books-container'); @@ -170,7 +170,7 @@ cardLink.style.width = '160px'; cardLink.style.height = '240px'; cardLink.dataset.bookId = book.id; - cardLink.href = readUrlTemplate.replace('/@(default(Guid))', `/${book.id}`); + cardLink.href = readUrlTemplate.replace('/@(default(Guid))', `/${book.id}`) + `?libraryId=${libraryId}`; // Opening the reader is conditional on the reader being available and enabled for the library, so the generic nav-link // navigation is intercepted and replaced by one that first checks the reading availability, warning instead of navigating // when the book cannot be read. @@ -195,7 +195,7 @@ cardLink.appendChild(image); cardLink.appendChild(titleSpan); - const detailsUrl = detailsUrlTemplate.replace('/@(default(Guid))', `/${book.id}`); + const detailsUrl = detailsUrlTemplate.replace('/@(default(Guid))', `/${book.id}`) + `?libraryId=${libraryId}`; const trigger = document.createElement('button'); trigger.type = 'button'; @@ -212,7 +212,7 @@ menu.className = 'card-actions-menu'; menu.setAttribute('role', 'menu'); menu.innerHTML = ` - ${jsLocalizedStrings.read} + ${jsLocalizedStrings.read} ${jsLocalizedStrings.viewDetails}`; // Menu entries navigate through the same AJAX navigation used by the nav-links, so that the persistent chrome keeps running. @@ -302,7 +302,7 @@ // Opens the reader of the book when it can be read, and warns the user otherwise; the navigation is done through the same // AJAX navigation used by the nav-links, so that the page is not reloaded (and the audio player is not interrupted). async function handleBookCardClickAsync(card) { - const availabilityUrl = availabilityUrlTemplate.replace('/@(default(Guid))', `/${card.dataset.bookId}`); + const availabilityUrl = availabilityUrlTemplate.replace('/@(default(Guid))', `/${card.dataset.bookId}`) + `?libraryId=${libraryId}`; const response = await fetch(availabilityUrl, { headers: { 'Accept': 'application/json', diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml index 94e3a10c..37bf2d59 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml @@ -10,7 +10,7 @@ the page, edit the theme files. This fallback keeps every feature working without styling, so that a broken theme is obvious to the user while the page still functions. -/library/written-content-library/books-library/books/{id} +/library/written-content-library/books-library/books/{bookId} *@ @using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary @@ -34,18 +34,23 @@ var genres = metadata?.Genres ?? []; var tags = metadata?.Tags ?? []; var isbns = Model.ISBNs ?? []; - var contributors = Model.Contributors ?? []; + var contributors = Model.Contributors ?? []; var ratings = Model.Ratings ?? []; - // Resolves the localized label of a contributor role category, keyed by its domain value. - Func categoryLabel = category => category switch + // The full set of canonical media contributor roles, mirroring the MediaContributorRole enum members, offered by the role combobox. + var contributorRoles = new[] + { + "Other", "Author", "Translator", "Illustrator", "Publisher", "Narrator", "Actor", "Director", "Screenwriter", + "Composer", "Lyricist", "Arranger", "Conductor", "Producer", "ExecutiveProducer", "Engineer", "Mixer", "Remixer", + "RecordLabel", "Vocals", "BackingVocals", "Guitar", "BassGuitar", "Drums", "Percussion", "Keyboards", "Piano", + "Synthesizer", "Strings", "Woodwinds", "Brass", "Choir", "Orchestrator" + }; + // Resolves the localized label of a contributor role, keyed by its canonical value. + Func roleLabel = role => role switch { "Publisher" => _localizer["PublisherRole"].Value, "Other" => _localizer["OtherRole"].Value, - "Author" => _localizer["Author"].Value, - "Translator" => _localizer["Translator"].Value, - "Illustrator" => _localizer["Illustrator"].Value, - "Narrator" => _localizer["Narrator"].Value, - _ => category ?? string.Empty + _ when !string.IsNullOrWhiteSpace(role) => _localizer[role].Value, + _ => string.Empty }; // The country of release carried by the book, keyed by its ISO code. var currentReleaseCountry = releaseInfo?.ReleaseCountry?.ToString() ?? string.Empty; @@ -408,9 +413,8 @@ - - - + + @@ -419,22 +423,19 @@ @foreach (var contributor in contributors) { - - + @@ -515,8 +516,8 @@ const bookId = '@bookId'; const libraryId = '@libraryId'; const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)'; - const saveUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { id = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); - const coverUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { id = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); + const saveUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.SAVE_BOOK, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); + const coverUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.UPDATE_BOOK_COVER, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}`; // The element references are captured once, so that the cleanup can unbind their listeners even after the AJAX navigator has swapped the content out of the document. const coverImage = document.getElementById('book-cover-image'); @@ -577,6 +578,7 @@ function buildPayload() { return { Id: bookId, + LibraryId: libraryId, Format: readComboboxValue('format-combobox') || null, Edition: readValue('edition-input') || null, VolumeNumber: readNumber('volume-number-input'), @@ -595,10 +597,7 @@ })), Contributors: Array.from(contributorsBody.querySelectorAll('.contributor-row')).map(row => ({ Name: { DisplayName: row.querySelector('.contributor-name').value.trim() || null }, - Role: { - Name: row.querySelector('.contributor-role').value.trim() || null, - Category: readRowComboboxValue(row, '.contributor-category-combobox') || null - } + Role: readRowComboboxValue(row, '.contributor-role-combobox') || null })), Ratings: Array.from(ratingsBody.querySelectorAll('.rating-row')).map(row => ({ Value: parseOptionalDecimal(row.querySelector('.rating-value').value), @@ -763,9 +762,9 @@ const isbn = isbnOptions.find(option => option.value === value); if (isbn) return isbn.label; - const category = contributorCategoryOptions.find(option => option.value === value); - if (category) - return category.label; + const role = contributorRoleOptions.find(option => option.value === value); + if (role) + return role.label; const source = ratingSourceOptions.find(option => option.value === value); if (source) return source.label; @@ -776,14 +775,9 @@ { value: 'Isbn10', label: @Json.Serialize(_localizer["Isbn10"].Value) }, { value: 'Isbn13', label: @Json.Serialize(_localizer["Isbn13"].Value) } ]; - const contributorCategoryOptions = [ - { value: 'Other', label: @Json.Serialize(_localizer["OtherRole"].Value) }, - { value: 'Author', label: @Json.Serialize(_localizer["Author"].Value) }, - { value: 'Translator', label: @Json.Serialize(_localizer["Translator"].Value) }, - { value: 'Illustrator', label: @Json.Serialize(_localizer["Illustrator"].Value) }, - { value: 'Publisher', label: @Json.Serialize(_localizer["PublisherRole"].Value) }, - { value: 'Narrator', label: @Json.Serialize(_localizer["Narrator"].Value) } - ]; + const contributorRoleOptions = @Html.Raw(System.Text.Json.JsonSerializer.Serialize( + contributorRoles.Select(role => new { value = role, label = roleLabel(role) }), + new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase })); const ratingSourceOptions = [ { value: 'User', label: @Json.Serialize(_localizer["User"].Value) }, { value: 'OpenLibrary', label: @Json.Serialize(_localizer["OpenLibrary"].Value) }, @@ -807,9 +801,8 @@ function addContributorRow() { contributorsBody.insertAdjacentHTML('beforeend', ` - - - + + `); } diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml index dd8e3272..93fe436f 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml @@ -42,11 +42,12 @@ let isInitialized = false; const bookId = '@Model.BookId'; - const manifestUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_MANIFEST, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); - const availabilityUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`); + const libraryId = '@Model.LibraryId'; + const manifestUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_MANIFEST, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}`; + const availabilityUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_AVAILABILITY, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}`; const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)'; - const sectionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_SECTION, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + '?locationRef='; - const resourceUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_RESOURCE, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + '?resourceKey='; + const sectionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_SECTION, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}&locationRef=`; + const resourceUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_RESOURCE, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}&resourceKey=`; // Escapes a string for safe interpolation into HTML markup; the table of contents labels and location references come from // the book file itself, so they are escaped before they are placed into innerHTML, keeping a malicious book from injecting markup. diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml index 9796d49c..70efbfcf 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/Error.cshtml @@ -7,7 +7,7 @@

Error.

An error occurred while processing your request.

-@if (Model.ShowRequestId) +@if (Model.ShouldShowRequestId) {

Request ID: @Model.RequestId diff --git a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js index 5f24564e..e1640b12 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/file-system-browser-dialog.js @@ -263,7 +263,7 @@ if (addressBarInput.value !== null && !addressBarInput.value.endsWith(pathSeparator)) addressBarInput.value += pathSeparator; } else { - const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/api-check-path-exists?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`); + const pathExistsResponse = await callApiGetAsync(`${clientBasePath}path/api-check-path-exists?path=${encodeURIComponent(path)}&shouldIncludeHiddenElements=${showHiddenElements}`); if (pathExistsResponse !== undefined && !pathExistsResponse.exists) { notificationService.show("Specified path does not exist!", NotificationType.ERROR); // TODO: should ask error message from server when translation is implemented return false; @@ -775,7 +775,7 @@ * @param {Function} callback - Function to call for each directory received. */ async function fetchFileSystemDirectoriesAsync(path, callback) { - await fetchJsonDataAsync(`${clientBasePath}directories/api-get-directories?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'Directory'); + await fetchJsonDataAsync(`${clientBasePath}directories/api-get-directories?path=${encodeURIComponent(path)}&shouldIncludeHiddenElements=${showHiddenElements}`, callback, 'Directory'); } /** @@ -784,7 +784,7 @@ * @param {Function} callback - Function to call for each file received. */ async function fetchFileSystemFilesAsync(path, callback) { - await fetchJsonDataAsync(`${clientBasePath}files/api-get-tree-files?path=${encodeURIComponent(path)}&includeHiddenElements=${showHiddenElements}`, callback, 'File'); + await fetchJsonDataAsync(`${clientBasePath}files/api-get-tree-files?path=${encodeURIComponent(path)}&shouldIncludeHiddenElements=${showHiddenElements}`, callback, 'File'); } /** diff --git a/src/Lumina.sln b/src/Lumina.sln index 52d41b20..7aedef91 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -29,138 +29,35 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{16E590D3 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{53B1231B-37F5-44BA-80D5-DBA979775F5C}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{ACD16983-F1BD-4A92-B282-95BA8C456F6A}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{19C1EE2F-0F4C-4BF6-B677-E0EC37AB3C72}" ProjectSection(SolutionItems) = preProject - ..\docs\CONTRIBUTING.md = ..\docs\CONTRIBUTING.md - ..\docs\INSTALL.md = ..\docs\INSTALL.md ..\LICENSE.md = ..\LICENSE.md ..\README.md = ..\README.md + ..\docs\CONTRIBUTING.md = ..\docs\CONTRIBUTING.md + ..\docs\INSTALL.md = ..\docs\INSTALL.md ..\docs\SOURCES.md = ..\docs\SOURCES.md ..\docs\USAGE.md = ..\docs\USAGE.md EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "technical", "technical", "{0C0E5A56-AD29-4D0B-AB87-E865F8B933E2}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api", "api", "{B045C2EC-3ACB-47D3-BE62-7AC334B023D9}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "technical", "technical", "{64570222-A5AC-49EE-BEBC-25D61B989A20}" ProjectSection(SolutionItems) = preProject - ..\docs\technical\api\Api.Book.md = ..\docs\technical\api\Api.Book.md EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{4F8D14A3-A465-4EC2-B175-A188B113AB99}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api", "api", "{D78A725D-C3AE-420B-ABA8-255A000D7324}" ProjectSection(SolutionItems) = preProject - ..\docs\technical\domain\Aggregates.FileSystemManagement.md = ..\docs\technical\domain\Aggregates.FileSystemManagement.md - ..\docs\technical\domain\Aggregates.VideoLibrary.md = ..\docs\technical\domain\Aggregates.VideoLibrary.md - ..\docs\technical\domain\Aggregates.WrittenContentLibrary.md = ..\docs\technical\domain\Aggregates.WrittenContentLibrary.md - ..\docs\technical\domain\Common.Metadata.md = ..\docs\technical\domain\Common.Metadata.md - ..\docs\technical\domain\Domain.md = ..\docs\technical\domain\Domain.md - ..\docs\technical\domain\UbiquitousLanguage.md = ..\docs\technical\domain\UbiquitousLanguage.md EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "requests", "requests", "{C17A1188-FA69-42BC-92E6-4F91D31B3A58}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "admin", "admin", "{459EF701-AB73-40ED-81E6-144D3587C667}" ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\http-client.env.json = ..\docs\technical\requests\http-client.env.json EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "books", "books", "{FAFD9E43-508B-4F20-8AA2-8CADA697ED2D}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authorization", "authorization", "{08113205-695B-4DA4-8355-6C5377BBD8C0}" ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\books\Add.http = ..\docs\technical\requests\books\Add.http - ..\docs\technical\requests\books\GetAll.http = ..\docs\technical\requests\books\GetAll.http + ..\docs\technical\api\admin\authorization\Api.Permissions.md = ..\docs\technical\api\admin\authorization\Api.Permissions.md + ..\docs\technical\api\admin\authorization\Api.Roles.md = ..\docs\technical\api\admin\authorization\Api.Roles.md EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{3F057926-562F-4EF4-BFC0-EE62372D4551}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Api.IntegrationTests\Lumina.Presentation.Api.IntegrationTests.csproj", "{3680DAFB-10BA-4A0F-AE40-620D06DAF617}" -EndProject -Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{D4C61542-FC91-47FA-B1D2-11CC99617454}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Contracts", "Lumina.Contracts\Lumina.Contracts.csproj", "{6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5DD47F82-699B-4E71-A10A-238E80EA5814}" - ProjectSection(SolutionItems) = preProject - ..\.editorconfig = ..\.editorconfig - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "templates", "templates", "{A0D07244-9CB2-4E30-85A5-97D520E4B9CC}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\templates\PULL_REQUEST_TEMPLATE.md = ..\docs\technical\templates\PULL_REQUEST_TEMPLATE.md - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Web", "Lumina.Presentation.Web\Lumina.Presentation.Web.csproj", "{613C74E8-720C-4205-8BA7-85B23D2E7881}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SecurityTests", "SecurityTests", "{8B06B1D2-80B9-490C-9A36-C7748F58B705}" -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("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "users-management", "users-management", "{D1B39EFF-99E7-41B9-9DA1-12AF385FFBE8}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\api\users-management\Api.Authentication.md = ..\docs\technical\api\users-management\Api.Authentication.md - ..\docs\technical\api\users-management\Api.Authorization.md = ..\docs\technical\api\users-management\Api.Authorization.md - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "users-management", "users-management", "{94C56402-0557-4941-BEB4-4AA53735CE89}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authentication", "authentication", "{3B057D42-7179-45CE-B813-3D13A658B43C}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\users-management\authentication\ChangePassword.http = ..\docs\technical\requests\users-management\authentication\ChangePassword.http - ..\docs\technical\requests\users-management\authentication\Login.http = ..\docs\technical\requests\users-management\authentication\Login.http - ..\docs\technical\requests\users-management\authentication\RecoverPassword.http = ..\docs\technical\requests\users-management\authentication\RecoverPassword.http - ..\docs\technical\requests\users-management\authentication\Register.http = ..\docs\technical\requests\users-management\authentication\Register.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authorization", "authorization", "{CA023F42-0264-4E00-9814-76A48A811136}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\users-management\authorization\AddRole.http = ..\docs\technical\requests\users-management\authorization\AddRole.http - ..\docs\technical\requests\users-management\authorization\DeleteRole.http = ..\docs\technical\requests\users-management\authorization\DeleteRole.http - ..\docs\technical\requests\users-management\authorization\GetAuthorization.http = ..\docs\technical\requests\users-management\authorization\GetAuthorization.http - ..\docs\technical\requests\users-management\authorization\GetPermissions.http = ..\docs\technical\requests\users-management\authorization\GetPermissions.http - ..\docs\technical\requests\users-management\authorization\GetRolePermissions.http = ..\docs\technical\requests\users-management\authorization\GetRolePermissions.http - ..\docs\technical\requests\users-management\authorization\GetRoles.http = ..\docs\technical\requests\users-management\authorization\GetRoles.http - ..\docs\technical\requests\users-management\authorization\GetUserPermissions.http = ..\docs\technical\requests\users-management\authorization\GetUserPermissions.http - ..\docs\technical\requests\users-management\authorization\GetUserRole.http = ..\docs\technical\requests\users-management\authorization\GetUserRole.http - ..\docs\technical\requests\users-management\authorization\UpdateRole.http = ..\docs\technical\requests\users-management\authorization\UpdateRole.http - ..\docs\technical\requests\users-management\authorization\UpdateUserRoleAndPermissions.http = ..\docs\technical\requests\users-management\authorization\UpdateUserRoleAndPermissions.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system-management", "file-system-management", "{2C55920F-0BCB-4C64-A1E6-56053F080806}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "directories", "directories", "{FBD8915E-DFE2-4C16-8B47-64383AB0719D}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\file-system-management\directories\GetDirectories.http = ..\docs\technical\requests\file-system-management\directories\GetDirectories.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "drives", "drives", "{DB498346-5F46-49FC-B2E9-8239C56791FF}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\file-system-management\drives\GetDrives.http = ..\docs\technical\requests\file-system-management\drives\GetDrives.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "files", "files", "{DBBB9C44-F4E8-4A1B-8D00-5CACE81B8BE0}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\file-system-management\files\GetFiles.http = ..\docs\technical\requests\file-system-management\files\GetFiles.http - ..\docs\technical\requests\file-system-management\files\GetTreeFiles.http = ..\docs\technical\requests\file-system-management\files\GetTreeFiles.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system", "file-system", "{42A27269-5C57-49E8-9AF0-F162807D7A95}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\file-system-management\file-system\GetType.http = ..\docs\technical\requests\file-system-management\file-system\GetType.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "path", "path", "{7675431D-8D8A-4148-AFA1-C4C17D71891B}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\file-system-management\path\CheckPathExists.http = ..\docs\technical\requests\file-system-management\path\CheckPathExists.http - ..\docs\technical\requests\file-system-management\path\CombinePath.http = ..\docs\technical\requests\file-system-management\path\CombinePath.http - ..\docs\technical\requests\file-system-management\path\GetPathParent.http = ..\docs\technical\requests\file-system-management\path\GetPathParent.http - ..\docs\technical\requests\file-system-management\path\GetPathRoot.http = ..\docs\technical\requests\file-system-management\path\GetPathRoot.http - ..\docs\technical\requests\file-system-management\path\GetPathSeparator.http = ..\docs\technical\requests\file-system-management\path\GetPathSeparator.http - ..\docs\technical\requests\file-system-management\path\SplitPath.http = ..\docs\technical\requests\file-system-management\path\SplitPath.http - ..\docs\technical\requests\file-system-management\path\ValidatePath.http = ..\docs\technical\requests\file-system-management\path\ValidatePath.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "thumbnails", "thumbnails", "{FC005908-27A7-4BDA-BD2A-B749A09727E0}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\requests\file-system-management\thumbnails\GetThumbnail.http = ..\docs\technical\requests\file-system-management\thumbnails\GetThumbnail.http - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system-management", "file-system-management", "{4DC31AC0-D305-4718-8FE1-C023AF6A7CA6}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system-management", "file-system-management", "{2FA735A6-2141-44AB-B34C-F65E4195B1EB}" ProjectSection(SolutionItems) = preProject ..\docs\technical\api\file-system-management\Api.Directories.md = ..\docs\technical\api\file-system-management\Api.Directories.md ..\docs\technical\api\file-system-management\Api.Drives.md = ..\docs\technical\api\file-system-management\Api.Drives.md @@ -170,7 +67,64 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system-management", "f ..\docs\technical\api\file-system-management\Api.Thumbnails.md = ..\docs\technical\api\file-system-management\Api.Thumbnails.md EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architecture", "{D93CA337-37D5-4A42-86B5-0A2410594A7A}" +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 + ..\docs\technical\api\library\audio-library\music-library\Api.Albums.md = ..\docs\technical\api\library\audio-library\music-library\Api.Albums.md + ..\docs\technical\api\library\audio-library\music-library\Api.Artists.md = ..\docs\technical\api\library\audio-library\music-library\Api.Artists.md + ..\docs\technical\api\library\audio-library\music-library\Api.Tracks.md = ..\docs\technical\api\library\audio-library\music-library\Api.Tracks.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", "{2CC7A70F-E08F-4C4F-9B0E-237AE5620C22}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\library\management\Api.Libraries.md = ..\docs\technical\api\library\management\Api.Libraries.md + 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 + ..\docs\technical\api\library\written-content-library\book-library\Api.Books.md = ..\docs\technical\api\library\written-content-library\book-library\Api.Books.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "maintenance", "maintenance", "{20D6BC0D-3B1E-4521-9CD7-9679BA0DC02B}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\maintenance\Api.Health.md = ..\docs\technical\api\maintenance\Api.Health.md + ..\docs\technical\api\maintenance\Api.Initialization.md = ..\docs\technical\api\maintenance\Api.Initialization.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "plugins", "plugins", "{54B8A7F4-9F61-47AA-8A33-F3B890A311BA}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\plugins\Api.Plugins.md = ..\docs\technical\api\plugins\Api.Plugins.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scheduling", "scheduling", "{3BDAA2C6-7D42-4279-8FBF-22F5A415D1FC}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\scheduling\Api.Scheduling.md = ..\docs\technical\api\scheduling\Api.Scheduling.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "themes", "themes", "{019980B6-51DB-4534-96FE-3E4DA528F4FE}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\themes\Api.Themes.md = ..\docs\technical\api\themes\Api.Themes.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "users-management", "users-management", "{DFF4A4CF-D736-4CA9-B970-AA85E62F4E51}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\api\users-management\Api.Authentication.md = ..\docs\technical\api\users-management\Api.Authentication.md + ..\docs\technical\api\users-management\Api.Authorization.md = ..\docs\technical\api\users-management\Api.Authorization.md + ..\docs\technical\api\users-management\Api.Settings.md = ..\docs\technical\api\users-management\Api.Settings.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architecture", "{BD7804E9-DD5D-45F9-B0CC-E0B9FFDF1B7D}" ProjectSection(SolutionItems) = preProject ..\docs\technical\architecture\1 system-context-diagram.puml = ..\docs\technical\architecture\1 system-context-diagram.puml ..\docs\technical\architecture\1 system-context-diagram.svg = ..\docs\technical\architecture\1 system-context-diagram.svg @@ -188,9 +142,11 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architectur ..\docs\technical\architecture\4.3 code-scheduler-diagram.svg = ..\docs\technical\architecture\4.3 code-scheduler-diagram.svg EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-knowledge-management", "architecture-knowledge-management", "{70B56088-6D3A-481E-9459-79AC6B16FEC1}" +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", "{788FADE4-342D-4919-8E5C-10CA8EDBE954}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", "architecture-decision-log", "{095CFEA5-8927-4347-9048-9BE0C8DC7CD0}" ProjectSection(SolutionItems) = preProject ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0001.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0001.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0002.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0002.md @@ -204,8 +160,291 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log", ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0010.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0010.md ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0011.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-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 EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\domain\Aggregates.AudioLibrary.md = ..\docs\technical\domain\Aggregates.AudioLibrary.md + ..\docs\technical\domain\Aggregates.FileSystemManagement.md = ..\docs\technical\domain\Aggregates.FileSystemManagement.md + ..\docs\technical\domain\Aggregates.VideoLibrary.md = ..\docs\technical\domain\Aggregates.VideoLibrary.md + ..\docs\technical\domain\Aggregates.WrittenContentLibrary.md = ..\docs\technical\domain\Aggregates.WrittenContentLibrary.md + ..\docs\technical\domain\Common.Metadata.md = ..\docs\technical\domain\Common.Metadata.md + ..\docs\technical\domain\Domain.md = ..\docs\technical\domain\Domain.md + ..\docs\technical\domain\UbiquitousLanguage.md = ..\docs\technical\domain\UbiquitousLanguage.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "requests", "requests", "{B45637D3-840C-4898-A047-C6FB568FFFE6}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\http-client.env.json = ..\docs\technical\requests\http-client.env.json + 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 + ..\docs\technical\requests\admin\authorization\permissions\GetPermissions.http = ..\docs\technical\requests\admin\authorization\permissions\GetPermissions.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "roles", "roles", "{3BCFBE37-A64D-4F3C-9D18-E37E89CB490F}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\admin\authorization\roles\AddRole.http = ..\docs\technical\requests\admin\authorization\roles\AddRole.http + ..\docs\technical\requests\admin\authorization\roles\DeleteRole.http = ..\docs\technical\requests\admin\authorization\roles\DeleteRole.http + ..\docs\technical\requests\admin\authorization\roles\GetRolePermissions.http = ..\docs\technical\requests\admin\authorization\roles\GetRolePermissions.http + ..\docs\technical\requests\admin\authorization\roles\GetRoles.http = ..\docs\technical\requests\admin\authorization\roles\GetRoles.http + ..\docs\technical\requests\admin\authorization\roles\UpdateRole.http = ..\docs\technical\requests\admin\authorization\roles\UpdateRole.http + 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 + ..\docs\technical\requests\file-system-management\directories\GetDirectories.http = ..\docs\technical\requests\file-system-management\directories\GetDirectories.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "drives", "drives", "{82D80C8B-593E-4E54-BDC2-26931EA3E2D6}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\file-system-management\drives\GetDrives.http = ..\docs\technical\requests\file-system-management\drives\GetDrives.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "files", "files", "{F6D1AE55-7A86-4854-8DA7-FD386CA4ABE5}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\file-system-management\files\GetFiles.http = ..\docs\technical\requests\file-system-management\files\GetFiles.http + ..\docs\technical\requests\file-system-management\files\GetTreeFiles.http = ..\docs\technical\requests\file-system-management\files\GetTreeFiles.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "file-system", "file-system", "{CD047DEA-454F-41E0-AD68-396A2940E55A}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\file-system-management\file-system\GetType.http = ..\docs\technical\requests\file-system-management\file-system\GetType.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "path", "path", "{9521E177-E2FE-4449-AD59-C1167E86AE81}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\file-system-management\path\CheckPathExists.http = ..\docs\technical\requests\file-system-management\path\CheckPathExists.http + ..\docs\technical\requests\file-system-management\path\CombinePath.http = ..\docs\technical\requests\file-system-management\path\CombinePath.http + ..\docs\technical\requests\file-system-management\path\GetPathParent.http = ..\docs\technical\requests\file-system-management\path\GetPathParent.http + ..\docs\technical\requests\file-system-management\path\GetPathRoot.http = ..\docs\technical\requests\file-system-management\path\GetPathRoot.http + ..\docs\technical\requests\file-system-management\path\GetPathSeparator.http = ..\docs\technical\requests\file-system-management\path\GetPathSeparator.http + ..\docs\technical\requests\file-system-management\path\SplitPath.http = ..\docs\technical\requests\file-system-management\path\SplitPath.http + ..\docs\technical\requests\file-system-management\path\ValidatePath.http = ..\docs\technical\requests\file-system-management\path\ValidatePath.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "thumbnails", "thumbnails", "{09E59FC0-1E79-4908-AB53-AF6A8E1A018A}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\file-system-management\thumbnails\GetThumbnail.http = ..\docs\technical\requests\file-system-management\thumbnails\GetThumbnail.http + 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 + ..\docs\technical\requests\library\audio-library\music-library\albums\AddAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\AddAlbum.http + ..\docs\technical\requests\library\audio-library\music-library\albums\DeleteAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\DeleteAlbum.http + ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbum.http + ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracks.http + ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http = ..\docs\technical\requests\library\audio-library\music-library\albums\GetAlbumTracksLite.http + ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http = ..\docs\technical\requests\library\audio-library\music-library\albums\UpdateAlbum.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "artists", "artists", "{F3818697-E304-491D-8BF3-4DAA1733B5F5}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\library\audio-library\music-library\artists\AddArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\AddArtist.http + ..\docs\technical\requests\library\audio-library\music-library\artists\DeleteArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\DeleteArtist.http + ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtist.http + ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistAlbums.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistAlbums.http + ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistAlbumsLite.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistAlbumsLite.http + ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtists.http + ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http = ..\docs\technical\requests\library\audio-library\music-library\artists\GetArtistsLite.http + ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http = ..\docs\technical\requests\library\audio-library\music-library\artists\UpdateArtist.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657B1-60DC-4E22-89D2-6212154D6BA8}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\AddTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", "{FDED0D4B-3FB6-42CA-AC73-76038F9DDF5E}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\library\management\AddLibrary.http = ..\docs\technical\requests\library\management\AddLibrary.http + ..\docs\technical\requests\library\management\CancelLibrariesScan.http = ..\docs\technical\requests\library\management\CancelLibrariesScan.http + ..\docs\technical\requests\library\management\CancelLibraryScan.http = ..\docs\technical\requests\library\management\CancelLibraryScan.http + ..\docs\technical\requests\library\management\DeleteLibrary.http = ..\docs\technical\requests\library\management\DeleteLibrary.http + ..\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\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 + ..\docs\technical\requests\library\management\ScanLibrary.http = ..\docs\technical\requests\library\management\ScanLibrary.http + ..\docs\technical\requests\library\management\UpdateLibrary.http = ..\docs\technical\requests\library\management\UpdateLibrary.http + 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 + ..\docs\technical\requests\library\written-content-library\book-library\books\AddBook.http = ..\docs\technical\requests\library\written-content-library\book-library\books\AddBook.http + ..\docs\technical\requests\library\written-content-library\book-library\books\GetBook.http = ..\docs\technical\requests\library\written-content-library\book-library\books\GetBook.http + ..\docs\technical\requests\library\written-content-library\book-library\books\GetBooks.http = ..\docs\technical\requests\library\written-content-library\book-library\books\GetBooks.http + ..\docs\technical\requests\library\written-content-library\book-library\books\GetBooksLite.http = ..\docs\technical\requests\library\written-content-library\book-library\books\GetBooksLite.http + ..\docs\technical\requests\library\written-content-library\book-library\books\UpdateBook.http = ..\docs\technical\requests\library\written-content-library\book-library\books\UpdateBook.http + ..\docs\technical\requests\library\written-content-library\book-library\books\UpdateBookCover.http = ..\docs\technical\requests\library\written-content-library\book-library\books\UpdateBookCover.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "reading", "reading", "{EC34148A-46DE-4A84-8365-85C951D0ED66}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingAvailability.http = ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingAvailability.http + ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingManifest.http = ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingManifest.http + ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingResource.http = ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingResource.http + ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingSection.http = ..\docs\technical\requests\library\written-content-library\book-library\books\reading\GetReadingSection.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "maintenance", "maintenance", "{72755888-3D28-40BE-8A21-6529E5B8FEE4}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\maintenance\CheckHealth.http = ..\docs\technical\requests\maintenance\CheckHealth.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "application-setup", "application-setup", "{8403EFA0-9B81-4FB6-826D-A24CB7B0A27C}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\maintenance\application-setup\CheckInitialization.http = ..\docs\technical\requests\maintenance\application-setup\CheckInitialization.http + ..\docs\technical\requests\maintenance\application-setup\SetupApplication.http = ..\docs\technical\requests\maintenance\application-setup\SetupApplication.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "plugins", "plugins", "{DA66D288-8458-4797-8E9D-57C177AE9C5F}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\plugins\GetLibraryArtworkProviders.http = ..\docs\technical\requests\plugins\GetLibraryArtworkProviders.http + ..\docs\technical\requests\plugins\GetLibraryBookReaders.http = ..\docs\technical\requests\plugins\GetLibraryBookReaders.http + ..\docs\technical\requests\plugins\GetLibraryMetadataProviders.http = ..\docs\technical\requests\plugins\GetLibraryMetadataProviders.http + ..\docs\technical\requests\plugins\GetPlugins.http = ..\docs\technical\requests\plugins\GetPlugins.http + ..\docs\technical\requests\plugins\GetPluginSettings.http = ..\docs\technical\requests\plugins\GetPluginSettings.http + ..\docs\technical\requests\plugins\InstallPlugin.http = ..\docs\technical\requests\plugins\InstallPlugin.http + ..\docs\technical\requests\plugins\ReorderLibraryArtworkProviders.http = ..\docs\technical\requests\plugins\ReorderLibraryArtworkProviders.http + ..\docs\technical\requests\plugins\ReorderLibraryMetadataProviders.http = ..\docs\technical\requests\plugins\ReorderLibraryMetadataProviders.http + ..\docs\technical\requests\plugins\SetLibraryArtworkProviderEnabled.http = ..\docs\technical\requests\plugins\SetLibraryArtworkProviderEnabled.http + ..\docs\technical\requests\plugins\SetLibraryBookReaderEnabled.http = ..\docs\technical\requests\plugins\SetLibraryBookReaderEnabled.http + ..\docs\technical\requests\plugins\SetLibraryMetadataProviderEnabled.http = ..\docs\technical\requests\plugins\SetLibraryMetadataProviderEnabled.http + ..\docs\technical\requests\plugins\UpdatePluginSettings.http = ..\docs\technical\requests\plugins\UpdatePluginSettings.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scheduling", "scheduling", "{A60EE169-1FBF-4085-AE4D-811CD18EF8EC}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\scheduling\AddScheduledJob.http = ..\docs\technical\requests\scheduling\AddScheduledJob.http + ..\docs\technical\requests\scheduling\FireScheduledJob.http = ..\docs\technical\requests\scheduling\FireScheduledJob.http + ..\docs\technical\requests\scheduling\GetScheduledJobHistory.http = ..\docs\technical\requests\scheduling\GetScheduledJobHistory.http + ..\docs\technical\requests\scheduling\GetScheduledJobs.http = ..\docs\technical\requests\scheduling\GetScheduledJobs.http + ..\docs\technical\requests\scheduling\GetSchedulerDisplayPreferences.http = ..\docs\technical\requests\scheduling\GetSchedulerDisplayPreferences.http + ..\docs\technical\requests\scheduling\RemoveScheduledJob.http = ..\docs\technical\requests\scheduling\RemoveScheduledJob.http + ..\docs\technical\requests\scheduling\StartScheduledJob.http = ..\docs\technical\requests\scheduling\StartScheduledJob.http + ..\docs\technical\requests\scheduling\StopScheduledJob.http = ..\docs\technical\requests\scheduling\StopScheduledJob.http + ..\docs\technical\requests\scheduling\UpdateSchedulerDisplayPreferences.http = ..\docs\technical\requests\scheduling\UpdateSchedulerDisplayPreferences.http + 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 + ..\docs\technical\requests\themes\management\DeleteTheme.http = ..\docs\technical\requests\themes\management\DeleteTheme.http + ..\docs\technical\requests\themes\management\InstallTheme.http = ..\docs\technical\requests\themes\management\InstallTheme.http + ..\docs\technical\requests\themes\management\RestoreTheme.http = ..\docs\technical\requests\themes\management\RestoreTheme.http + ..\docs\technical\requests\themes\management\SetCurrentTheme.http = ..\docs\technical\requests\themes\management\SetCurrentTheme.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "queries", "queries", "{FB8C9173-78BA-4C11-B698-4918537A5911}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\themes\queries\GetCurrentTheme.http = ..\docs\technical\requests\themes\queries\GetCurrentTheme.http + ..\docs\technical\requests\themes\queries\GetThemeArchive.http = ..\docs\technical\requests\themes\queries\GetThemeArchive.http + ..\docs\technical\requests\themes\queries\GetThemeAsset.http = ..\docs\technical\requests\themes\queries\GetThemeAsset.http + ..\docs\technical\requests\themes\queries\GetThemes.http = ..\docs\technical\requests\themes\queries\GetThemes.http + ..\docs\technical\requests\themes\queries\GetThemeSettings.http = ..\docs\technical\requests\themes\queries\GetThemeSettings.http + ..\docs\technical\requests\themes\queries\GetThemeTemplate.http = ..\docs\technical\requests\themes\queries\GetThemeTemplate.http + 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 + ..\docs\technical\requests\users-management\authentication\ChangePassword.http = ..\docs\technical\requests\users-management\authentication\ChangePassword.http + ..\docs\technical\requests\users-management\authentication\GetUsers.http = ..\docs\technical\requests\users-management\authentication\GetUsers.http + ..\docs\technical\requests\users-management\authentication\Login.http = ..\docs\technical\requests\users-management\authentication\Login.http + ..\docs\technical\requests\users-management\authentication\RecoverPassword.http = ..\docs\technical\requests\users-management\authentication\RecoverPassword.http + ..\docs\technical\requests\users-management\authentication\Register.http = ..\docs\technical\requests\users-management\authentication\Register.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "authorization", "authorization", "{69994895-991C-46BF-A13C-85CF62B519E5}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\users-management\authorization\GetAuthorization.http = ..\docs\technical\requests\users-management\authorization\GetAuthorization.http + ..\docs\technical\requests\users-management\authorization\GetUserPermissions.http = ..\docs\technical\requests\users-management\authorization\GetUserPermissions.http + ..\docs\technical\requests\users-management\authorization\GetUserRole.http = ..\docs\technical\requests\users-management\authorization\GetUserRole.http + ..\docs\technical\requests\users-management\authorization\UpdateUserRoleAndPermissions.http = ..\docs\technical\requests\users-management\authorization\UpdateUserRoleAndPermissions.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "settings", "settings", "{240E1B2A-08A3-439D-B8B2-4D9C18B4AF8A}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\requests\users-management\settings\GetUserSettings.http = ..\docs\technical\requests\users-management\settings\GetUserSettings.http + ..\docs\technical\requests\users-management\settings\UpdateUserSettings.http = ..\docs\technical\requests\users-management\settings\UpdateUserSettings.http + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "templates", "templates", "{279D354F-C362-4302-A265-A46FDB070565}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\templates\PULL_REQUEST_TEMPLATE.md = ..\docs\technical\templates\PULL_REQUEST_TEMPLATE.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "theming", "theming", "{F1DB0FEA-AF12-4F0E-9277-ADB024560937}" + ProjectSection(SolutionItems) = preProject + ..\docs\technical\theming\Theming.md = ..\docs\technical\theming\Theming.md + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IntegrationTests", "IntegrationTests", "{3F057926-562F-4EF4-BFC0-EE62372D4551}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Api.IntegrationTests", "..\tests\IntegrationTests\Lumina.Presentation.Api.IntegrationTests\Lumina.Presentation.Api.IntegrationTests.csproj", "{3680DAFB-10BA-4A0F-AE40-620D06DAF617}" +EndProject +Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{D4C61542-FC91-47FA-B1D2-11CC99617454}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Contracts", "Lumina.Contracts\Lumina.Contracts.csproj", "{6BD85BA8-B3C4-4D79-8858-F6D7676FF2CC}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5DD47F82-699B-4E71-A10A-238E80EA5814}" + ProjectSection(SolutionItems) = preProject + ..\.editorconfig = ..\.editorconfig + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lumina.Presentation.Web", "Lumina.Presentation.Web\Lumina.Presentation.Web.csproj", "{613C74E8-720C-4205-8BA7-85B23D2E7881}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SecurityTests", "SecurityTests", "{8B06B1D2-80B9-490C-9A36-C7748F58B705}" +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.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}" @@ -256,11 +495,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.Fixt EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.TestPlugin", "..\tests\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj", "{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "theming", "theming", "{2872042D-061F-4C76-8017-0A518A7E28A7}" - ProjectSection(SolutionItems) = preProject - ..\docs\technical\theming\Theming.md = ..\docs\technical\theming\Theming.md - EndProjectSection -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Epub", "..\plugins\Lumina.Plugins.Epub\Lumina.Plugins.Epub.csproj", "{EBE84E94-60C3-4D04-8802-F81ACA74DE21}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Pdf", "..\plugins\Lumina.Plugins.Pdf\Lumina.Plugins.Pdf.csproj", "{46E92994-64C6-44CE-8039-D930775C532A}" @@ -882,6 +1116,62 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution + {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} + {08113205-695B-4DA4-8355-6C5377BBD8C0} = {459EF701-AB73-40ED-81E6-144D3587C667} + {2FA735A6-2141-44AB-B34C-F65E4195B1EB} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {6A5D3BED-AE4A-4D26-B12A-5DE996152A64} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {252D7F8D-991F-4C62-9BB1-D13988D7B4E2} = {6A5D3BED-AE4A-4D26-B12A-5DE996152A64} + {81BD9DAE-9044-41AC-BBC4-1B09EF678D4E} = {252D7F8D-991F-4C62-9BB1-D13988D7B4E2} + {2CC7A70F-E08F-4C4F-9B0E-237AE5620C22} = {6A5D3BED-AE4A-4D26-B12A-5DE996152A64} + {2293B76C-F1EB-46A9-8F67-E88BAEA4FC0C} = {6A5D3BED-AE4A-4D26-B12A-5DE996152A64} + {52264424-9A8F-4E12-9A14-87F306C595C7} = {2293B76C-F1EB-46A9-8F67-E88BAEA4FC0C} + {20D6BC0D-3B1E-4521-9CD7-9679BA0DC02B} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {54B8A7F4-9F61-47AA-8A33-F3B890A311BA} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {3BDAA2C6-7D42-4279-8FBF-22F5A415D1FC} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {019980B6-51DB-4534-96FE-3E4DA528F4FE} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {DFF4A4CF-D736-4CA9-B970-AA85E62F4E51} = {D78A725D-C3AE-420B-ABA8-255A000D7324} + {BD7804E9-DD5D-45F9-B0CC-E0B9FFDF1B7D} = {64570222-A5AC-49EE-BEBC-25D61B989A20} + {61E7E9B9-3C47-4E62-B49E-AFE8D6DC8B5C} = {BD7804E9-DD5D-45F9-B0CC-E0B9FFDF1B7D} + {095CFEA5-8927-4347-9048-9BE0C8DC7CD0} = {61E7E9B9-3C47-4E62-B49E-AFE8D6DC8B5C} + {3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570} = {64570222-A5AC-49EE-BEBC-25D61B989A20} + {B45637D3-840C-4898-A047-C6FB568FFFE6} = {64570222-A5AC-49EE-BEBC-25D61B989A20} + {48BAE4E1-B3E7-4517-82BF-51D5B884E2E4} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {A9BD996E-E8E8-4C34-B792-5E6A00BD5938} = {48BAE4E1-B3E7-4517-82BF-51D5B884E2E4} + {7DC07C5C-4877-45DF-86C2-D93069EA7608} = {A9BD996E-E8E8-4C34-B792-5E6A00BD5938} + {3BCFBE37-A64D-4F3C-9D18-E37E89CB490F} = {A9BD996E-E8E8-4C34-B792-5E6A00BD5938} + {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {B6A1AB2C-766F-4DC2-894A-4DF1FE102AED} = {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} + {82D80C8B-593E-4E54-BDC2-26931EA3E2D6} = {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} + {F6D1AE55-7A86-4854-8DA7-FD386CA4ABE5} = {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} + {CD047DEA-454F-41E0-AD68-396A2940E55A} = {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} + {9521E177-E2FE-4449-AD59-C1167E86AE81} = {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} + {09E59FC0-1E79-4908-AB53-AF6A8E1A018A} = {6D5C6E19-67A1-4327-A958-1EC0DA6E9D7D} + {38048ADA-6830-4575-BDA6-C6D77E6D3E09} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {48201A6C-CE2B-47EC-AEC8-C202843D2CEB} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09} + {A65199DD-543E-4C18-A16A-215BD34962A5} = {48201A6C-CE2B-47EC-AEC8-C202843D2CEB} + {B4DF8E8D-C245-4E7C-B85B-B52935EDA93B} = {A65199DD-543E-4C18-A16A-215BD34962A5} + {F3818697-E304-491D-8BF3-4DAA1733B5F5} = {A65199DD-543E-4C18-A16A-215BD34962A5} + {B1B657B1-60DC-4E22-89D2-6212154D6BA8} = {A65199DD-543E-4C18-A16A-215BD34962A5} + {FDED0D4B-3FB6-42CA-AC73-76038F9DDF5E} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09} + {61824D19-B08C-45C6-95F8-716B5FDA183C} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09} + {0C975F46-8A47-48EC-91A0-2B222032C043} = {61824D19-B08C-45C6-95F8-716B5FDA183C} + {299D6BD8-A7AC-4913-AA0C-EE0A7AAF5B9A} = {0C975F46-8A47-48EC-91A0-2B222032C043} + {EC34148A-46DE-4A84-8365-85C951D0ED66} = {299D6BD8-A7AC-4913-AA0C-EE0A7AAF5B9A} + {72755888-3D28-40BE-8A21-6529E5B8FEE4} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {8403EFA0-9B81-4FB6-826D-A24CB7B0A27C} = {72755888-3D28-40BE-8A21-6529E5B8FEE4} + {DA66D288-8458-4797-8E9D-57C177AE9C5F} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {A60EE169-1FBF-4085-AE4D-811CD18EF8EC} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {4EC0F04D-6794-429D-8306-E72C4E64B1D9} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {698FA5E0-7220-4A8F-9695-224890B19FC1} = {4EC0F04D-6794-429D-8306-E72C4E64B1D9} + {FB8C9173-78BA-4C11-B698-4918537A5911} = {4EC0F04D-6794-429D-8306-E72C4E64B1D9} + {863E6DFF-B0F3-4CFA-8544-260346A7735A} = {B45637D3-840C-4898-A047-C6FB568FFFE6} + {0C679328-F15A-46A9-890C-DED45CDE4680} = {863E6DFF-B0F3-4CFA-8544-260346A7735A} + {69994895-991C-46BF-A13C-85CF62B519E5} = {863E6DFF-B0F3-4CFA-8544-260346A7735A} + {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} @@ -893,33 +1183,12 @@ Global {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} - {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} = {ACD16983-F1BD-4A92-B282-95BA8C456F6A} - {B045C2EC-3ACB-47D3-BE62-7AC334B023D9} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} - {4F8D14A3-A465-4EC2-B175-A188B113AB99} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} - {C17A1188-FA69-42BC-92E6-4F91D31B3A58} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} - {FAFD9E43-508B-4F20-8AA2-8CADA697ED2D} = {C17A1188-FA69-42BC-92E6-4F91D31B3A58} {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} - {A0D07244-9CB2-4E30-85A5-97D520E4B9CC} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} {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} - {D1B39EFF-99E7-41B9-9DA1-12AF385FFBE8} = {B045C2EC-3ACB-47D3-BE62-7AC334B023D9} - {94C56402-0557-4941-BEB4-4AA53735CE89} = {C17A1188-FA69-42BC-92E6-4F91D31B3A58} - {3B057D42-7179-45CE-B813-3D13A658B43C} = {94C56402-0557-4941-BEB4-4AA53735CE89} - {CA023F42-0264-4E00-9814-76A48A811136} = {94C56402-0557-4941-BEB4-4AA53735CE89} - {2C55920F-0BCB-4C64-A1E6-56053F080806} = {C17A1188-FA69-42BC-92E6-4F91D31B3A58} - {FBD8915E-DFE2-4C16-8B47-64383AB0719D} = {2C55920F-0BCB-4C64-A1E6-56053F080806} - {DB498346-5F46-49FC-B2E9-8239C56791FF} = {2C55920F-0BCB-4C64-A1E6-56053F080806} - {DBBB9C44-F4E8-4A1B-8D00-5CACE81B8BE0} = {2C55920F-0BCB-4C64-A1E6-56053F080806} - {42A27269-5C57-49E8-9AF0-F162807D7A95} = {2C55920F-0BCB-4C64-A1E6-56053F080806} - {7675431D-8D8A-4148-AFA1-C4C17D71891B} = {2C55920F-0BCB-4C64-A1E6-56053F080806} - {FC005908-27A7-4BDA-BD2A-B749A09727E0} = {2C55920F-0BCB-4C64-A1E6-56053F080806} - {4DC31AC0-D305-4718-8FE1-C023AF6A7CA6} = {B045C2EC-3ACB-47D3-BE62-7AC334B023D9} - {D93CA337-37D5-4A42-86B5-0A2410594A7A} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} - {70B56088-6D3A-481E-9459-79AC6B16FEC1} = {D93CA337-37D5-4A42-86B5-0A2410594A7A} - {788FADE4-342D-4919-8E5C-10CA8EDBE954} = {70B56088-6D3A-481E-9459-79AC6B16FEC1} {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} @@ -944,7 +1213,6 @@ Global {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {65AA7896-2DE2-4F07-A1B2-C1E1774521C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} - {2872042D-061F-4C76-8017-0A518A7E28A7} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} {EBE84E94-60C3-4D04-8802-F81ACA74DE21} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {46E92994-64C6-44CE-8039-D930775C532A} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {A4BD890A-5959-4A9E-9FCA-CDCCE27B8662} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} @@ -960,4 +1228,4 @@ Global GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} EndGlobalSection -EndGlobal +EndGlobal \ No newline at end of file diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs new file mode 100644 index 00000000..1e717757 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +///

+/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AlbumLiteRowFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the album. + /// Optional. The title of the album. + /// Optional. The number of tracks of the release. + /// The created . + public AlbumLiteRow Create( + Guid? id = null, + string? title = null, + int? totalTracks = null) + { + return new AlbumLiteRow + { + Id = id ?? _faker.Random.Guid(), + Title = title ?? _faker.Music.Genre(), + TotalTracks = totalTracks ?? _faker.Random.Int(1, 30) + }; + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs new file mode 100644 index 00000000..671ca538 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistLiteRowFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the artist. + /// Optional. The name of the artist. + /// The created . + public ArtistLiteRow Create( + Guid? id = null, + string? name = null) + { + return new ArtistLiteRow + { + Id = id ?? _faker.Random.Guid(), + Name = name ?? _faker.Name.FullName() + }; + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs new file mode 100644 index 00000000..d7414256 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class TrackLiteRowFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the track. + /// 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. + /// Whether the disc number should be included, or forced to . + /// The created . + public TrackLiteRow Create( + Guid? id = null, + string? title = null, + int? trackNumber = null, + int? discNumber = null, + bool includeDiscNumber = true) + { + return new TrackLiteRow + { + Id = id ?? _faker.Random.Guid(), + Title = title ?? _faker.Lorem.Sentence(), + TrackNumber = trackNumber ?? _faker.Random.Int(1, 30), + DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : 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/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs new file mode 100644 index 00000000..67048e20 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLiteRowFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the book. + /// Optional. The title of the book. + /// Optional. The release year of the book. + /// Optional. The path of the cover image of the book. + /// The created . + public BookLiteRow Create( + Guid? id = null, + string? title = null, + int? releaseYear = null, + string? coverPath = null) + { + return new BookLiteRow + { + Id = id ?? _faker.Random.Guid(), + Title = title ?? _faker.Lorem.Sentence(), + ReleaseYear = releaseYear, + CoverPath = coverPath + }; + } + + /// + /// 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/Authorization/RoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs index 234cc401..1404aeeb 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs @@ -23,17 +23,17 @@ public class RoleEntityFixture /// Optional. The Id of the role. /// Optional. The name of the role. /// Optional. The role permission associations of the role. - /// Whether the role permission associations should be included, or forced to an empty collection. /// Optional. The Id of the user that created the role. /// Optional. The time and date when the role was added. + /// Whether the role permission associations should be included, or forced to an empty collection. /// The created . public RoleEntity Create( Guid? id = null, string? roleName = null, IEnumerable? rolePermissions = null, - bool includeRolePermissions = false, Guid? createdBy = null, - DateTime? createdOnUtc = null) + DateTime? createdOnUtc = null, + bool includeRolePermissions = false) { return new Faker() .CustomInstantiator(faker => new RoleEntity diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs index a0cc7ad3..e3182acb 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.Setup; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -26,7 +27,7 @@ public class GenreEntityFixture string? name = null, bool includeName = true) { - return new GenreEntity(includeName ? name ?? _faker.Lorem.Word() : null); + return new GenreEntity(includeName ? name ?? _faker.UniqueName() : null); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs index 1985f046..e7f41759 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.Setup; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -26,7 +27,7 @@ public class TagEntityFixture string? name = null, bool includeName = true) { - return new TagEntity(includeName ? name ?? _faker.Lorem.Word() : null); + return new TagEntity(includeName ? name ?? _faker.UniqueName() : null); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntityFixture.cs new file mode 100644 index 00000000..5b138826 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntityFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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 AlbumContributorEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the participation. + /// Optional. The Id of the album the contributor participated in. + /// Optional. The Id of the media contributor. + /// Optional. The role the contributor played in the album. + /// Optional. The Id of the user that created the participation. + /// The created . + public AlbumContributorEntity Create( + Guid? id = null, + Guid? albumId = null, + Guid? mediaContributorId = null, + MediaContributorRole? role = null, + Guid? createdBy = null) + { + return new AlbumContributorEntity + { + Id = id ?? Guid.NewGuid(), + AlbumId = albumId ?? Guid.NewGuid(), + MediaContributorId = mediaContributorId ?? Guid.NewGuid(), + Role = role ?? _faker.PickRandom(), + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = createdBy ?? Guid.NewGuid(), + UpdatedOnUtc = _faker.Random.Bool() ? _faker.Date.Recent() : null, + UpdatedBy = _faker.Random.Bool() ? Guid.NewGuid() : null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// Optional. The Id of the album the contributors participated in. + /// List of configured instances. + public List CreateMany(int count = 3, Guid? albumId = null) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(albumId: albumId))]; + } +} 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 new file mode 100644 index 00000000..e7c7b23b --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntityFixture.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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 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 AlbumEntityFixture +{ + private readonly Faker _faker = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the album. + /// Optional. The Id of the artist that owns the album. + /// Optional. The Id of the media library that owns the album. + /// Optional. The title of the album. + /// Optional. The tracks of the album. + /// Optional. The original release date of the album. + /// Optional. The original release year of the album. + /// Optional. The re-release date of the album. + /// Optional. The re-release year of the album. + /// Optional. The barcode of the album. + /// Optional. The original title of the album. + /// Optional. A brief description or summary of the album. + /// Optional. The language code of the album. + /// Optional. The language name of the album. + /// Optional. The language native name of the album. + /// Optional. The original language code of the album. + /// Optional. The original language name of the album. + /// Optional. The original language native name of the album. + /// Optional. The release type of the album. + /// Optional. The release status of the album. + /// Optional. The total number of discs of the album. + /// Optional. The media format of the album. + /// Optional. The catalog number of the album. + /// Optional. The MusicBrainz release identifier of the album. + /// Optional. The MusicBrainz release group identifier of the album. + /// Optional. The MusicBrainz release artist identifier of the album. + /// Whether the album should own a generated track, or no track at all. + /// Whether the owned metadata collections (Tags, Genres, Contributors, Ratings) should be included, or forced to empty collections. + /// Whether the original release date should be included, or forced to . + /// 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 . + /// Whether the barcode 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 language of the album should be included, or forced to . + /// Whether the original language of the album should be included, or forced to . + /// Whether the release type 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 media format 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 . + /// The created . + public AlbumEntity Create( + Guid? id = null, + Guid? artistId = null, + Guid? libraryId = null, + string? title = null, + List? tracks = null, + DateOnly? originalReleaseDate = null, + int? originalReleaseYear = null, + DateOnly? reReleaseDate = null, + int? reReleaseYear = null, + string? barcode = null, + string? originalTitle = null, + string? description = null, + string? languageCode = null, + string? languageName = null, + string? languageNativeName = null, + string? originalLanguageCode = null, + string? originalLanguageName = null, + string? originalLanguageNativeName = null, + MusicReleaseType? releaseType = null, + MusicReleaseStatus? releaseStatus = null, + int? totalDiscs = null, + MusicMediaFormat? mediaFormat = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + bool includeTracks = true, + bool includeMetadata = true, + bool includeOriginalReleaseDate = true, + bool includeOriginalReleaseYear = true, + bool includeReReleaseDate = true, + bool includeReReleaseYear = true, + bool includeBarcode = true, + bool includeOriginalTitle = true, + bool includeDescription = true, + bool includeLanguage = true, + bool includeOriginalLanguage = true, + bool includeReleaseType = true, + bool includeReleaseStatus = true, + bool includeTotalDiscs = true, + bool includeMediaFormat = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true) + { + Guid resolvedId = id ?? Guid.NewGuid(); + Guid resolvedArtistId = artistId ?? Guid.NewGuid(); + Guid resolvedLibraryId = libraryId ?? Guid.NewGuid(); + const int MAXIMUM_RELEASE_YEAR = 2026; + int resolvedOriginalReleaseYear = originalReleaseYear ?? Random.Shared.Next(1900, MAXIMUM_RELEASE_YEAR); + int resolvedReReleaseYearUpperBound = Math.Max(resolvedOriginalReleaseYear + 1, MAXIMUM_RELEASE_YEAR); + int resolvedReReleaseYear = reReleaseYear ?? Random.Shared.Next(resolvedOriginalReleaseYear, resolvedReReleaseYearUpperBound); + DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? _faker.DateOnlyBetween(new DateOnly(resolvedOriginalReleaseYear, 1, 1), new DateOnly(resolvedOriginalReleaseYear, 12, 31)); + DateOnly resolvedReReleaseDate = reReleaseDate ?? _faker.DateOnlyBetween(resolvedReReleaseYear == resolvedOriginalReleaseYear ? resolvedOriginalReleaseDate : new DateOnly(resolvedReReleaseYear, 1, 1), new DateOnly(resolvedReReleaseYear, 12, 31)); + List resolvedTracks = tracks ?? (includeTracks ? [_trackEntityFixture.Create(albumId: resolvedId, libraryId: resolvedLibraryId, includeMetadata: includeMetadata, includeOriginalReleaseDate: includeOriginalReleaseDate, includeOriginalReleaseYear: includeOriginalReleaseYear, includeReReleaseDate: includeReReleaseDate, includeReReleaseYear: includeReReleaseYear)] : []); + + return new Faker() + .CustomInstantiator(f => new AlbumEntity + { + Id = resolvedId, + ArtistId = resolvedArtistId, + LibraryId = resolvedLibraryId, + Title = default!, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = null + }) + .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.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) + .RuleFor(x => x.ReReleaseDate, includeReReleaseDate ? resolvedReReleaseDate : (DateOnly?)null) + .RuleFor(x => x.ReReleaseYear, includeReReleaseYear ? resolvedReReleaseYear : (int?)null) + .RuleFor(x => x.ReleaseCountry, f => f.PickRandom()) + .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.LanguageCode, f => includeLanguage ? (languageCode ?? f.Random.String2(2)) : null) + .RuleFor(x => x.LanguageName, f => includeLanguage ? (languageName ?? f.Random.String2(f.Random.Number(1, 50))) : null) + .RuleFor(x => x.LanguageNativeName, f => includeLanguage ? (languageNativeName ?? f.Random.String2(f.Random.Number(1, 50))) : null) + .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.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.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) + .RuleFor(x => x.Tags, f => includeMetadata ? [.. _tagEntityFixture.CreateMany(f.Random.Number(1, 3))] : []) + .RuleFor(x => x.Genres, f => includeMetadata ? [.. _genreEntityFixture.CreateMany(f.Random.Number(1, 3))] : []) + .RuleFor(x => x.Contributors, f => includeMetadata ? _albumContributorEntityFixture.CreateMany(f.Random.Number(1, 3), albumId: resolvedId) : []) + .RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) + .RuleFor(x => x.Tracks, resolvedTracks) + .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) + .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) + .Generate(); + } + + /// + /// 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/ArtistContributorEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistContributorEntityFixture.cs new file mode 100644 index 00000000..33b55492 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistContributorEntityFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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 ArtistContributorEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the participation. + /// Optional. The Id of the artist the contributor participated in. + /// Optional. The Id of the media contributor. + /// Optional. The role the contributor played in the artist. + /// Optional. The Id of the user that created the participation. + /// The created . + public ArtistContributorEntity Create( + Guid? id = null, + Guid? artistId = null, + Guid? mediaContributorId = null, + MediaContributorRole? role = null, + Guid? createdBy = null) + { + return new ArtistContributorEntity + { + Id = id ?? Guid.NewGuid(), + ArtistId = artistId ?? Guid.NewGuid(), + MediaContributorId = mediaContributorId ?? Guid.NewGuid(), + Role = role ?? _faker.PickRandom(), + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = createdBy ?? Guid.NewGuid(), + UpdatedOnUtc = _faker.Random.Bool() ? _faker.Date.Recent() : null, + UpdatedBy = _faker.Random.Bool() ? Guid.NewGuid() : null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// Optional. The Id of the artist the contributors participated in. + /// List of configured instances. + public List CreateMany(int count = 3, Guid? artistId = null) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(artistId: artistId))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs new file mode 100644 index 00000000..db9dedae --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntityFixture.cs @@ -0,0 +1,82 @@ +#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 class. +/// +[ExcludeFromCodeCoverage] +public class ArtistEntityFixture +{ + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly ArtistContributorEntityFixture _artistContributorEntityFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the artist. + /// Optional. The Id of the media library that owns the artist. + /// Optional. The name of the artist. + /// Optional. The website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The albums of the artist. + /// Whether the artist should own a generated album, or no album at all. + /// Whether the website should be included, or forced to . + /// Whether the MusicBrainz identifier should be included, or forced to . + /// Whether the artist should own a generated media contributor, or none at all. + /// Whether the owned metadata collections of the generated album should be included, or forced to empty collections. + /// The created . + public ArtistEntity Create( + Guid? id = null, + Guid? libraryId = null, + string? name = null, + string? website = null, + Guid? musicBrainzArtistId = null, + List? albums = null, + bool includeAlbums = true, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeContributors = true, + bool includeMetadata = true) + { + Guid resolvedId = id ?? Guid.NewGuid(); + Guid resolvedLibraryId = libraryId ?? Guid.NewGuid(); + List resolvedAlbums = albums ?? (includeAlbums ? [_albumEntityFixture.Create(artistId: resolvedId, libraryId: resolvedLibraryId, includeMetadata: includeMetadata)] : []); + + return new Faker() + .CustomInstantiator(f => new ArtistEntity + { + Id = resolvedId, + LibraryId = resolvedLibraryId, + Name = default!, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = null + }) + .RuleFor(x => x.Name, f => name ?? f.Name.FullName()) + .RuleFor(x => x.Website, f => includeWebsite ? (website ?? f.Internet.Url()) : null) + .RuleFor(x => x.MusicBrainzArtistId, f => includeMusicBrainzArtistId ? (musicBrainzArtistId ?? f.Random.Guid()) : null) + .RuleFor(x => x.Albums, resolvedAlbums) + .RuleFor(x => x.Contributors, f => includeContributors ? _artistContributorEntityFixture.CreateMany(f.Random.Number(1, 3), artistId: resolvedId) : []) + .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) + .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) + .Generate(); + } + + /// + /// 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/AudioRatingEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AudioRatingEntityFixture.cs new file mode 100644 index 00000000..9d04a636 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AudioRatingEntityFixture.cs @@ -0,0 +1,59 @@ +#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 AudioRatingEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The rating value of the audio media element. + /// Optional. The maximum possible rating value of the audio media element. + /// Optional. The source of the audio rating. + /// Optional. The number of votes that contributed to the audio rating. + /// Whether the value should be included, or forced to . + /// Whether the maximum value should be included, or forced to . + /// Whether the source should be included, or forced to . + /// Whether the vote count should be included, or forced to . + /// The created . + public AudioRatingEntity Create( + decimal? value = null, + decimal? maxValue = null, + AudioRatingSource? source = null, + int? voteCount = null, + bool includeValue = true, + bool includeMaxValue = true, + bool includeSource = true, + bool includeVoteCount = true) + { + return new AudioRatingEntity( + includeValue ? (value ?? _faker.Random.Decimal(1, 5)) : null, + includeMaxValue ? (maxValue ?? 5) : null, + includeSource ? (source ?? _faker.PickRandom()) : null, + includeVoteCount ? (voteCount ?? _faker.Random.Number(1, 1000)) : 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/TrackContributorEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackContributorEntityFixture.cs new file mode 100644 index 00000000..3a1030e2 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackContributorEntityFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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 TrackContributorEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the participation. + /// Optional. The Id of the track the contributor participated in. + /// Optional. The Id of the media contributor. + /// Optional. The role the contributor played in the track. + /// Optional. The Id of the user that created the participation. + /// The created . + public TrackContributorEntity Create( + Guid? id = null, + Guid? trackId = null, + Guid? mediaContributorId = null, + MediaContributorRole? role = null, + Guid? createdBy = null) + { + return new TrackContributorEntity + { + Id = id ?? Guid.NewGuid(), + TrackId = trackId ?? Guid.NewGuid(), + MediaContributorId = mediaContributorId ?? Guid.NewGuid(), + Role = role ?? _faker.PickRandom(), + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = createdBy ?? Guid.NewGuid(), + UpdatedOnUtc = _faker.Random.Bool() ? _faker.Date.Recent() : null, + UpdatedBy = _faker.Random.Bool() ? Guid.NewGuid() : null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// Optional. The Id of the track the contributors participated in. + /// List of configured instances. + public List CreateMany(int count = 3, Guid? trackId = null) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(trackId: trackId))]; + } +} 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 new file mode 100644 index 00000000..3b039dc2 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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 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 TrackEntityFixture +{ + private readonly Faker _faker = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the track. + /// Optional. The Id of the album that owns the track. + /// Optional. The Id of the media library that owns the track. + /// Optional. The file system path of the track. + /// Optional. The title of the track. + /// Optional. The number of the track on its disc. + /// Optional. The original release date of the track. + /// Optional. The original release year of the track. + /// Optional. The re-release date of the track. + /// Optional. The re-release year of the track. + /// Whether the owned metadata collections (Tags, Genres, Moods, ISRCs, Contributors, Ratings) should be included, or forced to empty collections. + /// Whether the original release date should be included, or forced to . + /// Whether the original release year should be included, or forced to . + /// Whether the re-release date should be included, or forced to . + /// Whether the re-release year should be included, or forced to . + /// The created . + public TrackEntity Create( + Guid? id = null, + Guid? albumId = null, + Guid? libraryId = null, + string? path = null, + string? title = null, + int? trackNumber = null, + DateOnly? originalReleaseDate = null, + int? originalReleaseYear = null, + DateOnly? reReleaseDate = null, + int? reReleaseYear = null, + bool includeMetadata = true, + bool includeOriginalReleaseDate = true, + bool includeOriginalReleaseYear = true, + bool includeReReleaseDate = true, + bool includeReReleaseYear = true) + { + Guid resolvedId = id ?? Guid.NewGuid(); + Guid resolvedAlbumId = albumId ?? Guid.NewGuid(); + Guid resolvedLibraryId = libraryId ?? Guid.NewGuid(); + const int MAXIMUM_RELEASE_YEAR = 2026; + int resolvedOriginalReleaseYear = originalReleaseYear ?? Random.Shared.Next(1900, MAXIMUM_RELEASE_YEAR); + int resolvedReReleaseYearUpperBound = Math.Max(resolvedOriginalReleaseYear + 1, MAXIMUM_RELEASE_YEAR); + int resolvedReReleaseYear = reReleaseYear ?? Random.Shared.Next(resolvedOriginalReleaseYear, resolvedReReleaseYearUpperBound); + DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? _faker.DateOnlyBetween(new DateOnly(resolvedOriginalReleaseYear, 1, 1), new DateOnly(resolvedOriginalReleaseYear, 12, 31)); + DateOnly resolvedReReleaseDate = reReleaseDate ?? _faker.DateOnlyBetween(resolvedReReleaseYear == resolvedOriginalReleaseYear ? resolvedOriginalReleaseDate : new DateOnly(resolvedReReleaseYear, 1, 1), new DateOnly(resolvedReReleaseYear, 12, 31)); + + return new Faker() + .CustomInstantiator(f => new TrackEntity + { + Id = resolvedId, + AlbumId = resolvedAlbumId, + LibraryId = resolvedLibraryId, + Path = default!, + Title = default!, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = null + }) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Title, f => title ?? f.Random.String2(f.Random.Number(1, 255))) + .RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255))) + .RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000))) + .RuleFor(x => x.OriginalReleaseDate, includeOriginalReleaseDate ? resolvedOriginalReleaseDate : null) + .RuleFor(x => x.OriginalReleaseYear, includeOriginalReleaseYear ? resolvedOriginalReleaseYear : null) + .RuleFor(x => x.ReReleaseDate, includeReReleaseDate ? resolvedReReleaseDate : null) + .RuleFor(x => x.ReReleaseYear, includeReReleaseYear ? resolvedReReleaseYear : null) + .RuleFor(x => x.ReleaseCountry, f => f.PickRandom()) + .RuleFor(x => x.ReleaseVersion, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.LanguageCode, f => f.Random.String2(2)) + .RuleFor(x => x.LanguageName, f => f.Random.String2(f.Random.Number(1, 50))) + .RuleFor(x => x.LanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) + .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.DurationInSeconds, Random.Shared.Next(60, 7200)) + .RuleFor(x => x.SampleRate, f => f.PickRandom(44100, 48000, 96000)) + .RuleFor(x => x.Channels, f => f.PickRandom(1, 2, 6)) + .RuleFor(x => x.BitDepth, Random.Shared.Next(8, 32)) + .RuleFor(x => x.AudioCodec, f => f.PickRandom("FLAC", "MP3", "AAC", "ALAC")) + .RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411)) + .RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20)) + .RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3)) + .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.MusicBrainzRecordingId, f => f.Random.Guid()) + .RuleFor(x => x.MusicBrainzTrackId, f => f.Random.Guid()) + .RuleFor(x => x.MusicBrainzWorkId, f => f.Random.Guid()) + .RuleFor(x => x.Tags, f => includeMetadata ? [.. _tagEntityFixture.CreateMany(f.Random.Number(1, 3))] : []) + .RuleFor(x => x.Genres, f => includeMetadata ? [.. _genreEntityFixture.CreateMany(f.Random.Number(1, 3))] : []) + .RuleFor(x => x.Moods, f => includeMetadata ? _trackMoodEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) + .RuleFor(x => x.Isrcs, f => includeMetadata ? _trackIsrcEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) + .RuleFor(x => x.Contributors, f => includeMetadata ? _trackContributorEntityFixture.CreateMany(f.Random.Number(1, 3), trackId: resolvedId) : []) + .RuleFor(x => x.Ratings, f => includeMetadata ? _audioRatingEntityFixture.CreateMany(f.Random.Number(1, 3)) : []) + .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) + .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) + .Generate(); + } + + /// + /// 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/TrackIsrcEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackIsrcEntityFixture.cs new file mode 100644 index 00000000..df274af2 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackIsrcEntityFixture.cs @@ -0,0 +1,46 @@ +#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 TrackIsrcEntityFixture +{ + private const string LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private const string ALPHANUMERICS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private const string DIGITS = "0123456789"; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the ISRC. + /// The created . + public TrackIsrcEntity Create(string? value = null) + { + // ISRC codes follow the domain format: two letters, three alphanumeric characters and seven digits. + return new TrackIsrcEntity(value ?? ( + _faker.Random.String2(2, LETTERS) + + _faker.Random.String2(3, ALPHANUMERICS) + + _faker.Random.String2(7, DIGITS))); + } + + /// + /// 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/TrackMoodEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackMoodEntityFixture.cs new file mode 100644 index 00000000..02103714 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackMoodEntityFixture.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 TrackMoodEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the mood. + /// The created . + public TrackMoodEntity Create( + string? name = null) + { + return new TrackMoodEntity(name ?? _faker.Lorem.Word()); + } + + /// + /// 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/MediaContributors/BookContributorEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookContributorEntityFixture.cs similarity index 78% rename from tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/BookContributorEntityFixture.cs rename to tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookContributorEntityFixture.cs index 6645f6ed..15a268b2 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaContributors/BookContributorEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookContributorEntityFixture.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; @@ -8,7 +8,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; /// /// Fixture class for the class. @@ -24,23 +24,20 @@ public class BookContributorEntityFixture /// Optional. The Id of the participation. /// Optional. The Id of the book the contributor participated in. /// Optional. The Id of the media contributor. - /// Optional. The display name of the role the contributor played in the book. - /// Optional. The canonical category of the role the contributor played in the book. + /// Optional. The role the contributor played in the book. /// The created . public BookContributorEntity Create( Guid? id = null, Guid? bookId = null, Guid? mediaContributorId = null, - string? roleName = null, - MediaContributorRoleCategory? roleCategory = null) + MediaContributorRole? role = null) { return new BookContributorEntity { Id = id ?? Guid.NewGuid(), BookId = bookId ?? Guid.NewGuid(), MediaContributorId = mediaContributorId ?? Guid.NewGuid(), - RoleName = roleName ?? _faker.Lorem.Word(), - RoleCategory = roleCategory ?? _faker.PickRandom(), + Role = role ?? MediaContributorRole.Author, CreatedOnUtc = _faker.Date.Past(), CreatedBy = Guid.NewGuid(), UpdatedOnUtc = null, 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 bb961f1a..c8edfd88 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 @@ -18,7 +18,6 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Wr [ExcludeFromCodeCoverage] public class BookEntityFixture { - private readonly Random _random = new(); private readonly Faker _faker = new(); /// @@ -39,8 +38,8 @@ public class BookEntityFixture string? originalTitle = null, bool includeMetadata = true) { - int releaseYear = _random.Next(2000, 2010); - int reReleaseYear = _random.Next(2010, 2020); + int releaseYear = Random.Shared.Next(2000, 2010); + int reReleaseYear = Random.Shared.Next(2010, 2020); return new Faker() .RuleFor(x => x.Id, f => id ?? f.Random.Guid()) @@ -64,12 +63,12 @@ public class BookEntityFixture .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.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) - .RuleFor(x => x.PageCount, _random.Next(100, 300)) + .RuleFor(x => x.PageCount, Random.Shared.Next(100, 300)) .RuleFor(x => x.Format, f => f.PickRandom()) .RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.VolumeNumber, _random.Next(1, 3)) + .RuleFor(x => x.VolumeNumber, Random.Shared.Next(1, 3)) .RuleFor(x => x.ASIN, f => f.Random.String2(10)) - .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) + .RuleFor(x => x.GoodreadsId, Random.Shared.Next(100000, 500000).ToString()) .RuleFor(x => x.LCCN, CreateLCCN) .RuleFor(x => x.OCLCNumber, CreateOCLCNumber) .RuleFor(x => x.OpenLibraryId, CreateOpenLibraryId) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs index c5c2ddda..b13b15f0 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingEntityFixture.cs @@ -16,7 +16,6 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Wr [ExcludeFromCodeCoverage] public class BookRatingEntityFixture { - private readonly Random _random = new(); private readonly Faker _faker = new(); /// @@ -36,10 +35,10 @@ public class BookRatingEntityFixture bool includeValues = true) { return new BookRatingEntity( - includeValues ? (value ?? _random.Next(1, 5)) : null, + includeValues ? (value ?? Random.Shared.Next(1, 5)) : null, includeValues ? (maxValue ?? 5) : null, includeValues ? (source ?? _faker.PickRandom()) : null, - includeValues ? (voteCount ?? _random.Next(1, 1000)) : null + includeValues ? (voteCount ?? Random.Shared.Next(1, 1000)) : null ); } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs index 6208cb12..8a23f5fc 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Themes/ThemeEntityFixture.cs @@ -26,17 +26,17 @@ public class ThemeEntityFixture /// Optional author of the theme. /// Optional version of the theme. /// Optional preview image path of the theme, or when the theme has no preview. - /// Whether the preview path should be included, or forced to . /// Optional source the theme was installed from. /// Optional value indicating whether the theme is the currently active one. - /// Whether the currently active flag should be included, or forced to . /// Optional value indicating whether the theme was soft deleted. /// Optional UTC timestamp when the theme was installed. /// Optional UTC timestamp when the entity was created. /// Optional Id of the user that created the entity. /// Optional UTC timestamp when the entity was updated. - /// Whether the updated-on timestamp should be included, or forced to . /// Optional Id of the user that updated the entity. + /// Whether the preview path should be included, or forced to . + /// Whether the currently active flag should be included, or forced to . + /// Whether the updated-on timestamp should be included, or forced to . /// Whether the updated-by user Id should be included, or forced to . /// A configured instance. public ThemeEntity Create( @@ -47,17 +47,17 @@ public class ThemeEntityFixture string? author = null, string? version = null, string? previewPath = null, - bool includePreviewPath = false, ThemeInstallSource? installSource = null, bool? isCurrent = null, - bool includeIsCurrent = false, bool? isDeleted = null, DateTime? installedAtUtc = null, DateTime? createdOnUtc = null, Guid? createdBy = null, DateTime? updatedOnUtc = null, - bool includeUpdatedOnUtc = false, Guid? updatedBy = null, + bool includePreviewPath = false, + bool includeIsCurrent = false, + bool includeUpdatedOnUtc = false, bool includeUpdatedBy = false) { Guid resolvedCreatedBy = createdBy ?? Guid.NewGuid(); 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 61710769..f6432ad8 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 @@ -29,9 +29,9 @@ public class UserEntityFixture /// Optional Id to pin, or to generate a random one. /// Optional user role association to pin when including it. /// Optional user permission associations to pin when including them. + /// 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 collection of libraries to pin for the user, or to generate them based on . /// The created user entity. public UserEntity Create( int libraryCount = 0, @@ -40,9 +40,9 @@ public class UserEntityFixture Guid? id = null, UserRoleEntity? userRole = null, IEnumerable? userPermissions = null, + ICollection? libraries = null, bool includeUserRole = false, - bool includeUserPermissions = false, - ICollection? libraries = null) + bool includeUserPermissions = false) { Guid userId = id ?? Guid.NewGuid(); ICollection resolvedLibraries = libraries ?? (libraryCount > 0 diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs index 2e912ee2..2ba93d7b 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeManifestDtoFixture.cs @@ -25,8 +25,8 @@ public class ThemeManifestDtoFixture /// Optional author of the theme. /// Optional version of the theme. /// Optional preview image path of the theme, or when the theme has no preview. - /// Whether the preview path should be included, or forced to . /// Optional template mappings of the theme. + /// Whether the preview path should be included, or forced to . /// A configured instance. public ThemeManifestDto Create( int? schemaVersion = null, @@ -36,8 +36,8 @@ public class ThemeManifestDtoFixture string? author = null, string? version = null, string? preview = null, - bool includePreview = false, - Dictionary? templates = null) + Dictionary? templates = null, + bool includePreview = false) { return new Faker() .CustomInstantiator(f => new ThemeManifestDto diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs b/tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs index 2ceb6d84..dc417c68 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Setup/BogusExtensions.cs @@ -35,4 +35,18 @@ public static class BogusExtensions DateTime endDateTime = end.ToDateTime(TimeOnly.MinValue); return System.DateOnly.FromDateTime(faker.Date.Between(startDateTime, endDateTime)); } + + /// + /// Adds unique name generation support to the class, so that shared lookup tables never receive duplicate primary keys. + /// + /// The faker instance to extend. + /// A unique name of at most 50 characters. + public static string UniqueName(this Faker faker) + { + 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.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs index 2c775852..663664e7 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryFixture.cs @@ -18,9 +18,9 @@ public class GetDirectoriesQueryFixture /// Creates a random valid query to get directories. /// /// Optional. The file system path. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created query to get directories. - public GetDirectoriesQuery Create(string? path = null, bool includeHiddenElements = false) + public GetDirectoriesQuery Create(string? path = null, bool shouldIncludeHiddenElements = false) { return new Faker() .CustomInstantiator(f => new GetDirectoriesQuery( @@ -28,7 +28,7 @@ public class GetDirectoriesQueryFixture default )) .RuleFor(x => x.Path, f => path ?? f.System.DirectoryPath()) - .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + .RuleFor(x => x.ShouldIncludeHiddenElements, f => shouldIncludeHiddenElements); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs index fc1877af..19c9fcad 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryFixture.cs @@ -18,9 +18,9 @@ public class GetFilesQueryFixture /// Creates a random valid query to get files. /// /// Optional. The file system path. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created query to get files. - public GetFilesQuery Create(string? path = null, bool includeHiddenElements = false) + public GetFilesQuery Create(string? path = null, bool shouldIncludeHiddenElements = false) { return new Faker() .CustomInstantiator(f => new GetFilesQuery( @@ -28,7 +28,7 @@ public class GetFilesQueryFixture default )) .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) - .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + .RuleFor(x => x.ShouldIncludeHiddenElements, f => shouldIncludeHiddenElements); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs index 195ee6ee..a4b52be9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryFixture.cs @@ -18,9 +18,9 @@ public class GetTreeFilesQueryFixture /// Creates a random valid query to get tree files. /// /// Optional. The file system path. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created query to get tree files. - public GetTreeFilesQuery Create(string? path = null, bool includeHiddenElements = false) + public GetTreeFilesQuery Create(string? path = null, bool shouldIncludeHiddenElements = false) { return new Faker() .CustomInstantiator(f => new GetTreeFilesQuery( @@ -28,7 +28,7 @@ public class GetTreeFilesQueryFixture default )) .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) - .RuleFor(x => x.IncludeHiddenElements, f => includeHiddenElements); + .RuleFor(x => x.ShouldIncludeHiddenElements, f => shouldIncludeHiddenElements); } /// 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 0fc9910a..008ab95b 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 @@ -18,9 +18,9 @@ public class CheckPathExistsQueryFixture /// Creates a random valid query to check if paths exist. /// /// Optional. The file system path. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created query. - public CheckPathExistsQuery Create(string? path = null, bool includeHiddenElements = true) + public CheckPathExistsQuery Create(string? path = null, bool shouldIncludeHiddenElements = true) { return new Faker() .CustomInstantiator(f => new CheckPathExistsQuery( @@ -28,7 +28,7 @@ public class CheckPathExistsQueryFixture default )) .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) - .RuleFor(x => x.IncludeHiddenElements, includeHiddenElements); + .RuleFor(x => x.ShouldIncludeHiddenElements, shouldIncludeHiddenElements); } /// 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 new file mode 100644 index 00000000..773d80c0 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandFixture.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddAlbumCommandFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + + /// + /// Creates a random valid command to add an album. + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The album metadata of the album. + /// Optional. The physical or digital medium of the album. + /// Optional. The barcode of the album. + /// Optional. The catalog 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 media contributors that performed on the album. + /// Optional. The ratings of the album. + /// Optional. The tracks of the album. + /// Optional. The Id of the album, when it already exists. + /// Whether the library Id should be included, or forced to . + /// 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 barcode should be included, or forced to . + /// Whether the catalog number 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 . + /// Whether the tracks should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// The created command to add an album. + public AddAlbumCommand Create( + string? libraryId = null, + string? artistId = null, + AlbumMetadataDto? metadata = null, + MusicMediaFormat? mediaFormat = null, + string? barcode = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, + List? tracks = null, + Guid? albumId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeMetadata = true, + bool includeMediaFormat = true, + bool includeBarcode = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeTracks = true, + bool includeAlbumId = true) + { + string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null; + string? resolvedArtistId = includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null; + + return new AddAlbumCommand( + resolvedLibraryId, + resolvedArtistId, + includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMediaFormat ? (mediaFormat ?? _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, + includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeTracks ? (tracks ?? GenerateTracks(resolvedLibraryId, resolvedArtistId)) : null, + includeAlbumId ? (albumId ?? _faker.Random.Guid()) : 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())]; + } + + /// + /// Generates the tracks of the album, tied to the album's library and artist identifiers. + /// + /// The Id of the media library the tracks belong to. + /// The Id of the artist the tracks belong to. + /// The generated tracks. + private List GenerateTracks(string? libraryId, string? artistId) + { + return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addTrackCommandFixture.Create(libraryId: libraryId, artistId: artistId))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandFixture.cs new file mode 100644 index 00000000..1d740915 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteAlbumCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The Id of the album to delete, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// The created . + public DeleteAlbumCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true) + { + return new DeleteAlbumCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs new file mode 100644 index 00000000..6f158dbc --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandFixture.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +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.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCommandFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid command to update an album. + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The Id of the 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 barcode of the album. + /// Optional. The catalog 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 media contributors that performed on the album. + /// Optional. The ratings of the album. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the metadata should be included, or forced to . + /// Whether the media format 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 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 command to update an album. + public UpdateAlbumCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + AlbumMetadataDto? metadata = null, + MusicMediaFormat? mediaFormat = null, + string? barcode = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeMetadata = true, + bool includeMediaFormat = true, + bool includeBarcode = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true, + bool includeContributors = true, + bool includeRatings = true) + { + return new UpdateAlbumCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMediaFormat ? (mediaFormat ?? _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, + includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.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.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryFixture.cs new file mode 100644 index 00000000..ec886392 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The Id of the album to get, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// The created . + public GetAlbumQuery Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true) + { + return new GetAlbumQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryFixture.cs new file mode 100644 index 00000000..c6e20583 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The Id of the album whose tracks are retrieved, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// The created . + public GetAlbumTracksQuery Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true) + { + return new GetAlbumTracksQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryFixture.cs new file mode 100644 index 00000000..2dfa84ca --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryFixture.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteQueryFixture +{ + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the album belongs to, taken from the route. + /// Optional. The Id of the artist the album belongs to, taken from the route. + /// Optional. The Id of the album whose tracks are retrieved, taken from the route. + /// Optional. The pagination data of the query. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the pagination data should be included, or forced to . + /// The created . + public GetAlbumTracksLiteQuery Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + PaginationDataDto? paginationData = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includePaginationData = true) + { + return new GetAlbumTracksLiteQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs new file mode 100644 index 00000000..39e59696 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandFixture.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +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.Fixtures.Core.DTO.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddArtistCommandFixture +{ + private readonly Faker _faker = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = 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 website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The media contributors that make up 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 website should be included, or forced to . + /// Whether the MusicBrainz identifier should be included, or forced to . + /// Whether the contributors 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, + string? website = null, + Guid? musicBrainzArtistId = null, + List? contributors = null, + List? albums = null, + bool includeLibraryId = true, + bool includeName = true, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeContributors = true, + bool includeAlbums = true) + { + string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null; + + return new AddArtistCommand( + resolvedLibraryId, + includeName ? (name ?? _faker.Name.FullName()) : null, + includeWebsite ? (website ?? _faker.Internet.Url()) : null, + includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeAlbums ? (albums ?? GenerateAlbums(resolvedLibraryId)) : 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())]; + } + + /// + /// Generates the albums of the artist, tied to the artist's library identifier. + /// + /// The Id of the media library the albums belong to. + /// The generated albums. + private List GenerateAlbums(string? libraryId) + { + return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addAlbumCommandFixture.Create(libraryId: libraryId))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandFixture.cs new file mode 100644 index 00000000..d7682aa1 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to, taken from the route. + /// Optional. The Id of the artist to delete, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// The created . + public DeleteArtistCommand Create( + string? libraryId = null, + string? artistId = null, + bool includeLibraryId = true, + bool includeArtistId = true) + { + return new DeleteArtistCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs new file mode 100644 index 00000000..43137c90 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandFixture.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +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.Fixtures.Core.DTO.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCommandFixture +{ + private readonly Faker _faker = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = 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 website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The media contributors that make up 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 website should be included, or forced to . + /// Whether the MusicBrainz identifier should be included, or forced to . + /// Whether the contributors 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, + string? website = null, + Guid? musicBrainzArtistId = null, + List? contributors = null, + List? albums = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeName = true, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeContributors = true, + bool includeAlbums = true) + { + string? resolvedLibraryId = includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null; + + return new UpdateArtistCommand( + resolvedLibraryId, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeName ? (name ?? _faker.Name.FullName()) : null, + includeWebsite ? (website ?? _faker.Internet.Url()) : null, + includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))]) : null, + includeAlbums ? (albums ?? GenerateAlbums(resolvedLibraryId)) : 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())]; + } + + /// + /// Generates the albums of the artist, tied to the artist's library identifier. + /// + /// The Id of the media library the albums belong to. + /// The generated albums. + private List GenerateAlbums(string? libraryId) + { + return [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _addAlbumCommandFixture.Create(libraryId: libraryId))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryFixture.cs new file mode 100644 index 00000000..06d3858a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to, taken from the route. + /// Optional. The Id of the artist to get, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// The created . + public GetArtistQuery Create( + string? libraryId = null, + string? artistId = null, + bool includeLibraryId = true, + bool includeArtistId = true) + { + return new GetArtistQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryFixture.cs new file mode 100644 index 00000000..ef0df975 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to, taken from the route. + /// Optional. The Id of the artist whose albums are retrieved, taken from the route. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// The created . + public GetArtistAlbumsQuery Create( + string? libraryId = null, + string? artistId = null, + bool includeLibraryId = true, + bool includeArtistId = true) + { + return new GetArtistAlbumsQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryFixture.cs new file mode 100644 index 00000000..bb13fe01 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteQueryFixture +{ + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the artist belongs to, taken from the route. + /// Optional. The Id of the artist whose albums are retrieved, taken from the route. + /// Optional. The pagination data of the query. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the pagination data should be included, or forced to . + /// The created . + public GetArtistAlbumsLiteQuery Create( + string? libraryId = null, + string? artistId = null, + PaginationDataDto? paginationData = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includePaginationData = true) + { + return new GetArtistAlbumsLiteQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryFixture.cs new file mode 100644 index 00000000..f8a2c06b --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsQueryFixture +{ + private readonly Faker _faker = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artists are retrieved, taken from the route. + /// Optional. The pagination data of the query. + /// Optional. The search term used to filter the artists by name. + /// Whether the library Id should be included, or forced to . + /// Whether the pagination data should be included, or forced to . + /// Whether the search term should be included, or forced to . + /// The created . + public GetArtistsQuery Create( + string? libraryId = null, + PaginationDataDto? paginationData = null, + string? searchTerm = null, + bool includeLibraryId = true, + bool includePaginationData = true, + bool includeSearchTerm = true) + { + return new GetArtistsQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null, + includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryFixture.cs new file mode 100644 index 00000000..7e6ddb02 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteQueryFixture +{ + private readonly Faker _faker = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artists are retrieved, taken from the route. + /// Optional. The pagination data of the query. + /// Optional. The search term used to filter the artists by name. + /// Whether the library Id should be included, or forced to . + /// Whether the pagination data should be included, or forced to . + /// Whether the search term should be included, or forced to . + /// The created . + public GetArtistsLiteQuery Create( + string? libraryId = null, + PaginationDataDto? paginationData = null, + string? searchTerm = null, + bool includeLibraryId = true, + bool includePaginationData = true, + bool includeSearchTerm = true) + { + return new GetArtistsLiteQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null, + includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : null); + } + + /// + /// Creates a list of . + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs new file mode 100644 index 00000000..8bee2fae --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandFixture.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class AddTrackCommandFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid command to add a track. + /// + /// Optional. The Id of the media library the track belongs to, taken from the route. + /// Optional. The Id of the artist the track belongs to, taken from the route. + /// Optional. The Id of the album the track belongs to, taken from the route. + /// Optional. The file system path of the track. + /// Optional. The audio metadata of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// 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 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. + /// Optional. The list of ratings for this track. + /// Optional. The Id of the track, when it already exists. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the path should be included, or forced to . + /// Whether the metadata should be included, or forced to . + /// Whether the track number should be included, or forced to . + /// Whether the disc number 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 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 . + /// Whether the ratings should be included, or forced to . + /// The created command to add a track. + public AddTrackCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + string? path = null, + AudioMetadataDto? metadata = null, + int? trackNumber = null, + int? discNumber = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + string? work = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + List? moods = null, + List? isrcs = null, + List? contributors = null, + List? ratings = null, + Guid? trackId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includePath = true, + bool includeMetadata = true, + bool includeTrackNumber = true, + bool includeDiscNumber = true, + bool includeScript = true, + bool includeKey = true, + bool includeBpm = true, + bool includeWork = true, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeMusicBrainzWorkId = true, + bool includeMoods = true, + bool includeIsrcs = true, + bool includeContributors = true, + bool includeRatings = true) + { + return new AddTrackCommand( + includeLibraryId ? libraryId ?? Guid.NewGuid().ToString() : null, + 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, + 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, + 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, + includeRatings ? ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3)) : null, + trackId); + } + + /// + /// 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/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandFixture.cs new file mode 100644 index 00000000..847137a9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteTrackCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the track belongs to. + /// Optional. The Id of the artist the album of the track belongs to. + /// Optional. The Id of the album the track belongs to. + /// Optional. The Id of the track to delete. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the track Id should be included, or forced to . + /// The created . + public DeleteTrackCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + string? trackId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeTrackId = true) + { + return new DeleteTrackCommand( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// 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/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs new file mode 100644 index 00000000..54bcd79b --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandFixture.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +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.Contracts.Fixtures.Core.DTO.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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackCommandFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid command to update a track. + /// + /// Optional. The Id of the media library the track belongs to. + /// Optional. The Id of the artist the track belongs to. + /// Optional. The Id of the album the track belongs to. + /// Optional. The Id of the track to update. + /// Optional. The file system path of the track. + /// Optional. The audio metadata of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// 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 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. + /// Optional. The ratings of the track. + /// Whether the disc number 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 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 . + /// Whether the contributors list should be included, or forced to . + /// Whether the ratings list should be included, or forced to . + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the track Id should be included, or forced to . + /// Whether the path should be included, or forced to . + /// Whether the track number should be included, or forced to . + /// The created command to update a track. + public UpdateTrackCommand Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + string? trackId = null, + string? path = null, + AudioMetadataDto? metadata = null, + int? trackNumber = null, + int? discNumber = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + string? work = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + List? moods = null, + List? isrcs = null, + List? contributors = null, + List? ratings = null, + bool includeDiscNumber = true, + bool includeScript = true, + bool includeKey = true, + bool includeBpm = true, + bool includeWork = true, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeMusicBrainzWorkId = true, + bool includeMoods = true, + bool includeIsrcs = true, + bool includeMetadata = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeTrackId = true, + bool includePath = true, + bool includeTrackNumber = true) + { + return new UpdateTrackCommand( + includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null, + includeArtistId ? (artistId ?? _faker.Random.Guid().ToString()) : null, + 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, + 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, + 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, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.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.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryFixture.cs new file mode 100644 index 00000000..2f8839d5 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the track belongs to. + /// Optional. The Id of the artist the album of the track belongs to. + /// Optional. The Id of the album the track belongs to. + /// Optional. The Id of the track to get. + /// Whether the library Id should be included, or forced to . + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// Whether the track Id should be included, or forced to . + /// The created . + public GetTrackQuery Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + string? trackId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeTrackId = true) + { + return new GetTrackQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of 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/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs index 86eabf20..c38bc3c0 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandFixture.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Contracts.DTO.MediaContributors; @@ -11,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Linq; #endregion @@ -24,7 +25,7 @@ public class AddBookCommandFixture { private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// @@ -50,10 +51,24 @@ public class AddBookCommandFixture /// Optional. The contributors of the book. /// Optional. The ratings of the book. /// Whether the metadata should be included, or forced to . - /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// Whether the format should be included, or forced to . + /// Whether the edition should be included, or forced to . + /// Whether the volume number should be included, or forced to . + /// Whether the ASIN should be included, or forced to . + /// Whether the Goodreads Id should be included, or forced to . + /// Whether the LCCN should be included, or forced to . + /// Whether the OCLC number should be included, or forced to . + /// Whether the Open Library Id should be included, or forced to . + /// Whether the LibraryThing Id should be included, or forced to . + /// Whether the Google Books Id should be included, or forced to . + /// Whether the Barnes and Noble Id should be included, or forced to . + /// Whether the Apple Books Id should be included, or forced to . + /// Whether the ISBNs 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 command to add a book. public AddBookCommand Create( - Guid? libraryId = null, + string? libraryId = null, string? path = null, WrittenContentMetadataDto? metadata = null, BookFormat? format = null, @@ -70,10 +85,24 @@ public class AddBookCommandFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null, bool includeMetadata = true, - bool includeOptionalProperties = true) + bool includeFormat = true, + bool includeEdition = true, + bool includeVolumeNumber = true, + bool includeAsin = true, + bool includeGoodreadsId = true, + bool includeLccn = true, + bool includeOclcNumber = true, + bool includeOpenLibraryId = true, + bool includeLibraryThingId = true, + bool includeGoogleBooksId = true, + bool includeBarnesAndNobleId = true, + bool includeAppleBooksId = true, + bool includeIsbns = true, + bool includeRatings = true, + bool includeContributors = true) { return new Faker() .CustomInstantiator(f => new AddBookCommand( @@ -97,25 +126,25 @@ public class AddBookCommandFixture default!, default! )) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid().ToString()) + .RuleFor(x => x.Path, f => path ?? Path.Combine(Path.GetTempPath(), "lumina-books", f.System.FileName())) .RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null) - .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) - .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Format, f => format ?? (includeFormat ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeEdition ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeVolumeNumber ? (float?)f.Random.Number(1, 3) : null)) .RuleFor(x => x.Series, series) - .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) - .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) - .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) - .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) - .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) - .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) - .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) - .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) - .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + .RuleFor(x => x.ASIN, f => asin ?? (includeAsin ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeGoodreadsId ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeLccn ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOclcNumber ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOpenLibraryId ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeLibraryThingId ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeGoogleBooksId ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeBarnesAndNobleId ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeAppleBooksId ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeIsbns ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeRatings ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeContributors ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs index ffe50efa..e5738e1f 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBook/UpdateBookCommandFixture.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; using Lumina.Contracts.DTO.Common; @@ -25,13 +25,14 @@ public class UpdateBookCommandFixture { private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// /// Creates a random valid command to update a book. /// - /// Optional. The Id of the book to update. + /// Optional. The Id of the media library the book belongs to. + /// Optional. The Id of the book to update. /// Optional. The written content metadata of the book. /// Optional. The format of the book. /// Optional. The edition of the book. @@ -50,10 +51,25 @@ public class UpdateBookCommandFixture /// Optional. The contributors of the book. /// Optional. The ratings of the book. /// Whether the metadata should be included, or forced to . - /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// Whether the format should be included, or forced to . + /// Whether the edition should be included, or forced to . + /// Whether the volume number should be included, or forced to . + /// Whether the ASIN should be included, or forced to . + /// Whether the Goodreads Id should be included, or forced to . + /// Whether the LCCN should be included, or forced to . + /// Whether the OCLC number should be included, or forced to . + /// Whether the Open Library Id should be included, or forced to . + /// Whether the LibraryThing Id should be included, or forced to . + /// Whether the Google Books Id should be included, or forced to . + /// Whether the Barnes and Noble Id should be included, or forced to . + /// Whether the Apple Books Id should be included, or forced to . + /// Whether the ISBNs 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 command to update a book. public UpdateBookCommand Create( - Guid? id = null, + string? libraryId = null, + string? bookId = null, WrittenContentMetadataDto? metadata = null, BookFormat? format = null, string? edition = null, @@ -69,13 +85,28 @@ public class UpdateBookCommandFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null, bool includeMetadata = true, - bool includeOptionalProperties = true) + bool includeFormat = true, + bool includeEdition = true, + bool includeVolumeNumber = true, + bool includeAsin = true, + bool includeGoodreadsId = true, + bool includeLccn = true, + bool includeOclcNumber = true, + bool includeOpenLibraryId = true, + bool includeLibraryThingId = true, + bool includeGoogleBooksId = true, + bool includeBarnesAndNobleId = true, + bool includeAppleBooksId = true, + bool includeIsbns = true, + bool includeRatings = true, + bool includeContributors = true) { return new Faker() .CustomInstantiator(f => new UpdateBookCommand( + default, default, default!, default, @@ -90,29 +121,30 @@ public class UpdateBookCommandFixture default, default, default, - default, + default!, default!, default!, default! )) - .RuleFor(x => x.Id, id ?? Guid.NewGuid()) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid().ToString()) + .RuleFor(x => x.BookId, bookId ?? Guid.NewGuid().ToString()) .RuleFor(x => x.Metadata, includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null) - .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) - .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Format, f => format ?? (includeFormat ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeEdition ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeVolumeNumber ? (float?)f.Random.Number(1, 3) : null)) .RuleFor(x => x.Series, series) - .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) - .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) - .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) - .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) - .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) - .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) - .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) - .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) - .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + .RuleFor(x => x.ASIN, f => asin ?? (includeAsin ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeGoodreadsId ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeLccn ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOclcNumber ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOpenLibraryId ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeLibraryThingId ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeGoogleBooksId ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeBarnesAndNobleId ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeAppleBooksId ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeIsbns ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeRatings ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeContributors ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs index c86d20d4..78764153 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/UpdateBookCover/UpdateBookCoverCommandFixture.cs @@ -19,19 +19,22 @@ public class UpdateBookCoverCommandFixture /// /// Creates a random valid . /// + /// Optional. The Id of the media library the book belongs to. /// Optional. The Id of the book whose cover is updated. /// Optional. The stream of the uploaded cover image file. /// Optional. The name of the uploaded cover image file. /// Whether the cover stream should be included, or forced to . /// The created . public UpdateBookCoverCommand Create( - Guid? bookId = null, + string? libraryId = null, + string? bookId = null, Stream? cover = null, string? fileName = null, bool includeCover = true) { return new UpdateBookCoverCommand( - bookId ?? Guid.NewGuid(), + libraryId ?? Guid.NewGuid().ToString(), + bookId ?? Guid.NewGuid().ToString(), includeCover ? (cover ?? CreateCoverStream()) : null, fileName ?? "cover.jpg" ); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs index 70635887..1c37fc5b 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryFixture.cs @@ -17,12 +17,14 @@ public class GetBookQueryFixture /// /// Creates a random valid . /// - /// Optional. The Id of the book to get. + /// Optional. The Id of the library the book belongs to. + /// Optional. The Id of the book to get. /// The created . public GetBookQuery Create( - Guid? id = null) + string? libraryId = null, + string? bookId = null) { - return new GetBookQuery(id ?? Guid.NewGuid()); + return new GetBookQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString()); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs index c57cfff0..06ca5f2f 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -19,36 +18,32 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo public class GetBooksQueryFixture { private readonly Faker _faker = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); /// /// Creates a random valid query to get books. /// - /// Optional. The Id of the media library whose books are retrieved. + /// Optional. The Id of the media library whose books are retrieved, taken from the route. /// Optional. The pagination data of the query. /// Optional. The search term used to filter results. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the library Id should be included, or forced to . /// Whether the pagination data should be included, or forced to . /// The created query to get books. public GetBooksQuery Create( - Guid? libraryId = null, + string? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, string? sortBy = null, SortOrder? sortOrder = null, + bool includeLibraryId = true, bool includePaginationData = true) { return new GetBooksQuery( - includePaginationData ? paginationData ?? new PaginationDataDto - { - CurrentPage = _faker.Random.Number(1, 100), - PerPage = _faker.Random.Number(1, 200) - } : null, - new LibraryFilterDto - { - LibraryId = libraryId ?? _faker.Random.Guid(), - SearchTerm = searchTerm - }, + includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null, + searchTerm, sortBy, sortOrder ?? _faker.PickRandom() ); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs index 1f2fce3c..d07ad7b9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs @@ -1,10 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -19,42 +18,38 @@ namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.Bo public class GetBooksLiteQueryFixture { private readonly Faker _faker = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); /// /// Creates a random valid query to get the lightweight details of books. /// - /// Optional. The Id of the media library whose books are retrieved. + /// Optional. The Id of the media library whose books are retrieved, taken from the route. /// Optional. The pagination data of the query. /// Optional. The search term used to filter results. /// Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker. /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the library Id should be included, or forced to . /// Whether the pagination data should be included, or forced to . /// The created query to get the lightweight details of books. public GetBooksLiteQuery Create( - Guid? libraryId = null, + string? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, string? filterAlphaKey = null, bool shouldIgnoreThePrefixForAlphaPicker = false, string? sortBy = null, SortOrder? sortOrder = null, + bool includeLibraryId = true, bool includePaginationData = true) { return new GetBooksLiteQuery( - includePaginationData ? paginationData ?? new PaginationDataDto - { - CurrentPage = _faker.Random.Number(1, 100), - PerPage = _faker.Random.Number(1, 200) - } : null, - new LibraryFilterDto - { - LibraryId = libraryId ?? _faker.Random.Guid(), - SearchTerm = searchTerm, - FilterAlphaKey = filterAlphaKey, - ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker - }, + includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null, + includePaginationData ? (paginationData ?? _paginationDataDtoFixture.Create()) : null, + searchTerm, + filterAlphaKey, + shouldIgnoreThePrefixForAlphaPicker, sortBy, sortOrder ?? _faker.PickRandom() ); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryFixture.cs index 6b06e6c5..ca203642 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryFixture.cs @@ -17,12 +17,14 @@ public class GetReadingAvailabilityQueryFixture /// /// Creates a random valid query to check the reading availability of a book. /// + /// Optional. The Id of the library the book belongs to. /// Optional. The Id of the book whose reading availability is checked. /// The created . public GetReadingAvailabilityQuery Create( - Guid? bookId = null) + string? libraryId = null, + string? bookId = null) { - return new GetReadingAvailabilityQuery(bookId ?? Guid.NewGuid()); + return new GetReadingAvailabilityQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString()); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryFixture.cs index ba58a8d5..9bb320a9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryFixture.cs @@ -17,12 +17,14 @@ public class GetReadingManifestQueryFixture /// /// Creates a random valid query to get the reading manifest of a book. /// + /// Optional. The Id of the library the book belongs to. /// Optional. The Id of the book whose reading manifest is retrieved. /// The created . public GetReadingManifestQuery Create( - Guid? bookId = null) + string? libraryId = null, + string? bookId = null) { - return new GetReadingManifestQuery(bookId ?? Guid.NewGuid()); + return new GetReadingManifestQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString()); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryFixture.cs index 1c486bc9..5573a064 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryFixture.cs @@ -17,14 +17,16 @@ public class GetReadingResourceQueryFixture /// /// Creates a random valid query to get a resource of a book. /// + /// Optional. The Id of the library the book belongs to. /// Optional. The Id of the book whose resource is retrieved. /// Optional. The opaque resource key of the resource. /// The created . public GetReadingResourceQuery Create( - Guid? bookId = null, + string? libraryId = null, + string? bookId = null, string? resourceKey = null) { - return new GetReadingResourceQuery(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}"); + return new GetReadingResourceQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString(), resourceKey ?? $"resource-{Guid.NewGuid():N}"); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryFixture.cs index 8d69929a..1cb7cd48 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryFixture.cs @@ -17,14 +17,16 @@ public class GetReadingSectionQueryFixture /// /// Creates a random valid query to get the content of a reading section of a book. /// + /// Optional. The Id of the library the book belongs to. /// Optional. The Id of the book whose reading section is retrieved. /// Optional. The opaque location reference of the reading section. /// The created . public GetReadingSectionQuery Create( - Guid? bookId = null, + string? libraryId = null, + string? bookId = null, string? locationRef = null) { - return new GetReadingSectionQuery(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}"); + return new GetReadingSectionQuery(libraryId ?? Guid.NewGuid().ToString(), bookId ?? Guid.NewGuid().ToString(), locationRef ?? $"section-{Guid.NewGuid():N}"); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/MoodDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/MoodDtoFixture.cs new file mode 100644 index 00000000..4e27ae47 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/MoodDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MoodDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the mood. + /// Whether the name should be included, or forced to . + /// The created . + public MoodDto Create( + string? name = null, + bool includeName = true) + { + return new MoodDto(includeName ? name ?? _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.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs index e0f65c2c..e9d5bc34 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -21,35 +21,27 @@ public class MediaContributorDtoFixture /// Creates a random valid . /// /// Optional. The display name of the media contributor. - /// Optional. The name of the role assigned to the media contributor. - /// Optional. The category of the role. + /// Optional. The canonical role assigned to the media contributor. /// Optional. The legal name of the media contributor. /// Whether the name should be included, or forced to . /// Whether the display name should be included, or forced to . /// Whether the legal name should be included, or forced to . /// Whether the role should be included, or forced to . - /// Whether the role name should be included, or forced to . - /// Whether the role category should be included, or forced to . /// The created . public MediaContributorDto Create( string? displayName = null, - string? roleName = null, - MediaContributorRoleCategory? roleCategory = null, + MediaContributorRole? role = null, string? legalName = null, bool includeName = true, bool includeDisplayName = true, bool includeLegalName = true, - bool includeRole = true, - bool includeRoleName = true, - bool includeRoleCategory = true) + bool includeRole = true) { return new MediaContributorDto( Name: includeName ? new MediaContributorNameDto( DisplayName: includeDisplayName ? displayName ?? _faker.Name.FullName() : null, LegalName: includeLegalName ? legalName : null) : null, - Role: includeRole ? new MediaContributorRoleDto( - Name: includeRoleName ? roleName ?? _faker.Commerce.Department() : null, - Category: includeRoleCategory ? roleCategory ?? _faker.PickRandom() : null) : null); + Role: includeRole ? role ?? _faker.PickRandom() : null); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorReferenceDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorReferenceDtoFixture.cs new file mode 100644 index 00000000..7b773afc --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorReferenceDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorReferenceDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media contributor. + /// Optional. The role the contributor played. + /// The created . + public MediaContributorReferenceDto Create(Guid? contributorId = null, MediaContributorRole? role = null) + { + return new MediaContributorReferenceDto( + ContributorId: contributorId ?? Guid.NewGuid(), + Role: role ?? _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.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs deleted file mode 100644 index 58c5243f..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs +++ /dev/null @@ -1,44 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorRoleDtoFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The name of the role assigned to the media contributor. - /// Optional. The category of the role. - /// The created . - public MediaContributorRoleDto Create( - string? name = null, - MediaContributorRoleCategory? category = null) - { - return new MediaContributorRoleDto( - name ?? _faker.Commerce.Department(), - category ?? _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.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/AudioRatingDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/AudioRatingDtoFixture.cs new file mode 100644 index 00000000..6db08376 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/AudioRatingDtoFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using AutoFixture; +using Lumina.Contracts.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; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingDtoFixture +{ + private readonly Fixture _fixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The rating value. + /// Optional. The maximum possible rating value. + /// Optional. The rating source. + /// Optional. The number of votes. + /// Whether the rating value should be included, or forced to . + /// Whether the maximum possible rating value should be included, or forced to . + /// Whether the rating source should be included, or forced to . + /// Whether the number of votes should be included, or forced to . + /// The created . + public AudioRatingDto Create( + decimal? value = null, + decimal? maxValue = null, + AudioRatingSource? source = null, + int? voteCount = null, + bool includeValue = true, + bool includeMaxValue = true, + bool includeSource = true, + bool includeVoteCount = true) + { + return new AudioRatingDto( + includeValue ? (value ?? Random.Shared.Next(1, 5)) : null, + includeMaxValue ? (maxValue ?? 5) : null, + includeSource ? (source ?? _fixture.Create()) : null, + includeVoteCount ? (voteCount ?? Random.Shared.Next(1, 1000)) : 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/AlbumMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs new file mode 100644 index 00000000..bc52b188 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDtoFixture.cs @@ -0,0 +1,165 @@ +#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 AlbumMetadataDtoFixture +{ + 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. A brief description or summary 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 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 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 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 AlbumMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + ReleaseInfoDto? releaseInfo = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + List? tags = null, + List? genres = null, + MusicReleaseType? releaseType = null, + MusicReleaseStatus? releaseStatus = null, + int? totalDiscs = null, + int? totalTracks = null, + bool includeTitle = true, + bool includeOriginalTitle = true, + bool includeDescription = true, + bool includeReleaseInfo = true, + bool includeLanguage = true, + bool includeOriginalLanguage = true, + bool includeTags = true, + bool includeGenres = true, + bool includeReleaseType = true, + bool includeReleaseStatus = true, + bool includeTotalDiscs = true, + bool includeTotalTracks = true) + { + return new AlbumMetadataDto( + includeTitle ? (title ?? _faker.Music.Genre()) : null, + includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null, + includeDescription ? (description ?? _faker.Lorem.Paragraph()) : 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, + includeReleaseStatus ? (releaseStatus ?? _faker.PickRandom()) : null, + includeTotalDiscs ? (totalDiscs ?? _faker.Random.Int(1, 3)) : null, + includeTotalTracks ? (totalTracks ?? _faker.Random.Int(1, 30)) : 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/AudioMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs new file mode 100644 index 00000000..c8eba087 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDtoFixture.cs @@ -0,0 +1,174 @@ +#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 AudioMetadataDtoFixture +{ + 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 audio. + /// Optional. The original title of the audio. + /// Optional. A brief description or summary 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 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. + /// 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 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 AudioMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + ReleaseInfoDto? releaseInfo = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + List? tags = null, + List? genres = 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 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 AudioMetadataDto( + includeTitle ? (title ?? _faker.Music.Genre()) : null, + includeOriginalTitle ? (originalTitle ?? _faker.Music.Genre()) : null, + includeDescription ? (description ?? _faker.Lorem.Paragraph()) : null, + includeReleaseInfo ? (releaseInfo ?? GenerateReleaseInfo()) : null, + includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, + includeOriginalLanguage ? (originalLanguage ?? _languageInfoDtoFixture.Create()) : null, + includeTags ? (tags ?? GenerateDistinctTags()) : null, + includeGenres ? (genres ?? GenerateDistinctGenres()) : 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); + } + + /// + /// 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/IsrcDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/IsrcDtoFixture.cs new file mode 100644 index 00000000..7ec98766 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/IsrcDtoFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +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 IsrcDtoFixture +{ + private const string LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private const string ALPHANUMERICS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private const string DIGITS = "0123456789"; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the ISRC. + /// Whether the value should be included, or forced to . + /// The created . + public IsrcDto Create( + string? value = null, + bool includeValue = true) + { + return new IsrcDto(includeValue ? value ?? GenerateValidIsrc() : 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())]; + } + + /// + /// Generates a random ISRC that satisfies the domain format: two letters, three alphanumeric characters and seven digits. + /// + /// The generated ISRC value. + private string GenerateValidIsrc() + { + return _faker.Random.String2(2, LETTERS) + + _faker.Random.String2(3, ALPHANUMERICS) + + _faker.Random.String2(7, DIGITS); + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs index e0861e5d..44157872 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs @@ -57,7 +57,12 @@ public class BookMetadataDtoFixture /// Optional. The ratings of the book. /// Optional. The path of the cover image of the book. /// Whether the title should be included, or forced to . - /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// Whether the release info 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 language should be included, or forced to . + /// Whether the format should be included, or forced to . + /// Whether the volume number should be included, or forced to . /// The created . public BookMetadataDto Create( string? title = null, @@ -88,26 +93,31 @@ public class BookMetadataDtoFixture List? ratings = null, string? coverImagePath = null, bool includeTitle = true, - bool includeOptionalProperties = true) + bool includeReleaseInfo = true, + bool includeGenres = true, + bool includeTags = true, + bool includeLanguage = true, + bool includeFormat = true, + bool includeVolumeNumber = true) { int releaseYear = _faker.Random.Int(1900, 2024); return new BookMetadataDto( - includeTitle ? title ?? (includeOptionalProperties ? _faker.Lorem.Sentence(3) : null) : null, + includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, originalTitle, description, - releaseInfo ?? (includeOptionalProperties ? _releaseInfoDtoFixture.Create( + includeReleaseInfo ? (releaseInfo ?? _releaseInfoDtoFixture.Create( originalReleaseDate: new DateOnly(releaseYear, 1, 1), originalReleaseYear: releaseYear, - releaseCountry: _faker.PickRandom()) : null), - genres ?? (includeOptionalProperties ? [_genreDtoFixture.Create()] : null), - tags ?? (includeOptionalProperties ? [_tagDtoFixture.Create()] : null), - language ?? (includeOptionalProperties ? _languageInfoDtoFixture.Create() : null), + releaseCountry: _faker.PickRandom())) : null, + includeGenres ? (genres ?? [_genreDtoFixture.Create()]) : null, + includeTags ? (tags ?? [_tagDtoFixture.Create()]) : null, + includeLanguage ? (language ?? _languageInfoDtoFixture.Create()) : null, originalLanguage, publisher, pageCount, - format ?? (includeOptionalProperties ? _faker.PickRandom() : null), + includeFormat ? (format ?? _faker.PickRandom()) : null, edition, - volumeNumber ?? (includeOptionalProperties ? _faker.Random.Int(1, 10) : null), + includeVolumeNumber ? (volumeNumber ?? _faker.Random.Int(1, 10)) : null, series, asin, goodreadsId, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs index cd594450..1ff90d12 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoFixture.cs @@ -17,7 +17,6 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary. public class BookRatingDtoFixture { private readonly Fixture _fixture = new(); - private readonly Random _random = new(); /// /// Creates a . @@ -26,20 +25,22 @@ public class BookRatingDtoFixture /// Optional. The maximum possible rating value. /// Optional. The rating source. /// Optional. The number of votes. - /// Whether the optional source and vote count should be randomized, or forced to . + /// Whether the source should be included, or forced to . + /// Whether the vote count should be included, or forced to . /// The created . public BookRatingDto Create( decimal? value = null, decimal? maxValue = null, BookRatingSource? source = null, int? voteCount = null, - bool includeOptionalProperties = true) + bool includeSource = true, + bool includeVoteCount = true) { return new BookRatingDto( - value ?? _random.Next(1, 5), + value ?? Random.Shared.Next(1, 5), maxValue ?? 5, - source ?? (includeOptionalProperties ? _fixture.Create() : null), - voteCount ?? (includeOptionalProperties ? _random.Next(1, 1000) : null) + includeSource ? (source ?? _fixture.Create()) : null, + includeVoteCount ? (voteCount ?? Random.Shared.Next(1, 1000)) : null ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs index 33184bca..1995bf64 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoFixture.cs @@ -15,7 +15,6 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary. [ExcludeFromCodeCoverage] public class IsbnDtoFixture { - private readonly Random _random = new(); /// /// Creates an with a random or explicitly requested format. @@ -50,7 +49,7 @@ public class IsbnDtoFixture { int[] digits = new int[9]; for (int i = 0; i < 9; i++) - digits[i] = _random.Next(0, 10); + digits[i] = Random.Shared.Next(0, 10); int sum = 0; for (int i = 0; i < 9; i++) @@ -68,10 +67,10 @@ public class IsbnDtoFixture /// A valid ISBN-13 value. private string GenerateValidIsbn13() { - string prefix = _random.Next(2) == 0 ? "978" : "979"; - string group = _random.Next(0, 99999).ToString().PadLeft(5, '0'); - string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0'); - string title = _random.Next(0, 99).ToString().PadLeft(2, '0'); + string prefix = Random.Shared.Next(2) == 0 ? "978" : "979"; + string group = Random.Shared.Next(0, 99999).ToString().PadLeft(5, '0'); + string publisher = Random.Shared.Next(0, 999999).ToString().PadLeft(6, '0'); + string title = Random.Shared.Next(0, 99).ToString().PadLeft(2, '0'); string isbn = $"{prefix}{group[..1]}{publisher}{title}"; int sum = 0; diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs index fd257126..aa257d7f 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs @@ -18,8 +18,10 @@ namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; [ExcludeFromCodeCoverage] public class WrittenContentMetadataDtoFixture { + private const int MINIMUM_RELEASE_YEAR = 1900; + private const int MAXIMUM_RELEASE_YEAR = 2026; + private readonly Faker _faker = new(); - private readonly Random _random = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); @@ -100,8 +102,8 @@ public class WrittenContentMetadataDtoFixture /// The created . private ReleaseInfoDto CreateReleaseInfo() { - int originalReleaseYear = _random.Next(1900, 2026); - int reReleaseYear = _random.Next(originalReleaseYear, 2026); + 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, diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs index 683ac580..a46e3d27 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs @@ -20,15 +20,15 @@ public class GetDirectoriesRequestFixture /// Creates a with default or random values. /// /// Optional. The file system path for which to get the directories. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created . public GetDirectoriesRequest Create( string? path = null, - bool? includeHiddenElements = null) + bool? shouldIncludeHiddenElements = null) { return new GetDirectoriesRequest( Path: path ?? _faker.System.FilePath(), - IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ShouldIncludeHiddenElements: shouldIncludeHiddenElements ?? _faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs index aa139a6d..2fed66cf 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetFilesRequestFixture.cs @@ -20,15 +20,15 @@ public class GetFilesRequestFixture /// Creates a with default or random values. /// /// Optional. The file system path for which to get the files. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created . public GetFilesRequest Create( string? path = null, - bool? includeHiddenElements = null) + bool? shouldIncludeHiddenElements = null) { return new GetFilesRequest( Path: path ?? _faker.System.FilePath(), - IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ShouldIncludeHiddenElements: shouldIncludeHiddenElements ?? _faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs index 6f5c67d2..ff79cf3f 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Files/GetTreeFilesRequestFixture.cs @@ -20,15 +20,15 @@ public class GetTreeFilesRequestFixture /// Creates a with default or random values. /// /// Optional. The file system path for which to get the tree files. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created . public GetTreeFilesRequest Create( string? path = null, - bool? includeHiddenElements = null) + bool? shouldIncludeHiddenElements = null) { return new GetTreeFilesRequest( Path: path ?? _faker.System.FilePath(), - IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ShouldIncludeHiddenElements: shouldIncludeHiddenElements ?? _faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs index 41682d4b..be4ce76b 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/FileSystemManagement/Path/CheckPathExistsRequestFixture.cs @@ -20,15 +20,15 @@ public class CheckPathExistsRequestFixture /// Creates a with default or random values. /// /// Optional. The path to check. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// The created . public CheckPathExistsRequest Create( string? path = null, - bool? includeHiddenElements = null) + bool? shouldIncludeHiddenElements = null) { return new CheckPathExistsRequest( Path: path ?? _faker.System.FilePath(), - IncludeHiddenElements: includeHiddenElements ?? _faker.Random.Bool() + ShouldIncludeHiddenElements: shouldIncludeHiddenElements ?? _faker.Random.Bool() ); } 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 new file mode 100644 index 00000000..2c5f4520 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestFixture.cs @@ -0,0 +1,101 @@ +#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.Tracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddAlbumRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid request to add an album. + /// + /// Optional. The album metadata of the album. + /// Optional. The physical or digital medium of the album. + /// Optional. The barcode of the album. + /// Optional. The catalog 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 media contributors that performed on the album. + /// Optional. The ratings of the album. + /// Optional. The tracks of the album. + /// Whether the metadata 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 tracks list should be included, or forced to . + /// Whether the media format 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 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, + MusicMediaFormat? mediaFormat = null, + string? barcode = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, + List? tracks = null, + bool includeMetadata = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeTracks = true, + bool includeMediaFormat = true, + bool includeBarcode = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true) + { + return new AddAlbumRequest( + includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, + includeCatalogNumber ? (catalogNumber ?? _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 ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeTracks ? (tracks ?? _addTrackRequestFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestFixture.cs new file mode 100644 index 00000000..829fbd00 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a with default or random values. + /// + /// Optional. The page of results to retrieve. + /// Optional. The maximum number of tracks to retrieve per page. + /// Whether the current page should be included, or forced to . + /// Whether the per page count should be included, or forced to . + /// The created . + public GetAlbumTracksLiteRequest Create( + int? currentPage = null, + int? perPage = null, + bool includeCurrentPage = true, + bool includePerPage = true) + { + return new GetAlbumTracksLiteRequest( + CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, + PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : 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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs new file mode 100644 index 00000000..cbf07c50 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestFixture.cs @@ -0,0 +1,93 @@ +#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.Albums; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid request to update an album. + /// + /// Optional. The album metadata of the album. + /// Optional. The physical or digital medium of the album. + /// Optional. The barcode of the album. + /// Optional. The catalog 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 media contributors that performed on the album. + /// Optional. The ratings of the album. + /// Whether the metadata 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 media format 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 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, + MusicMediaFormat? mediaFormat = null, + string? barcode = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, + bool includeMetadata = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeMediaFormat = true, + bool includeBarcode = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true) + { + return new UpdateAlbumRequest( + includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, + includeCatalogNumber ? (catalogNumber ?? _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 ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs new file mode 100644 index 00000000..df2aa7a4 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestFixture.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +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; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddArtistRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + /// + /// Creates a random valid request to add an artist. + /// + /// Optional. The name of the artist. + /// Optional. The website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The media contributors that make up the artist. + /// Optional. The albums of the artist. + /// Whether the name 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 contributors 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, + string? website = null, + Guid? musicBrainzArtistId = null, + List? contributors = null, + List? albums = null, + bool includeName = true, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeContributors = true, + bool includeAlbums = true) + { + return new AddArtistRequest( + includeName ? (name ?? _faker.Name.FullName()) : null, + includeWebsite ? (website ?? _faker.Internet.Url()) : null, + includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeAlbums ? (albums ?? _addAlbumRequestFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestFixture.cs new file mode 100644 index 00000000..0382c0ac --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid request to get the lightweight read models of the albums of an artist. + /// + /// Optional. The page of results to retrieve. + /// Optional. The maximum number of albums to retrieve per page. + /// Whether the current page should be included, or forced to . + /// Whether the per page count should be included, or forced to . + /// The created request to get the lightweight read models of the albums of an artist. + public GetArtistAlbumsLiteRequest Create( + int? currentPage = null, + int? perPage = null, + bool includeCurrentPage = true, + bool includePerPage = true) + { + return new GetArtistAlbumsLiteRequest( + includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, + includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : 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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestFixture.cs new file mode 100644 index 00000000..c513da38 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid request to get the lightweight read models of the artists of a media library. + /// + /// Optional. The page of results to retrieve. + /// Optional. The maximum number of artists to retrieve per page. + /// Optional. The search term used to filter the artists by name. + /// Whether the current page should be included, or forced to . + /// Whether the per page count should be included, or forced to . + /// Whether the search term should be included, or forced to . + /// The created request to get the lightweight read models of the artists of a media library. + public GetArtistsLiteRequest Create( + int? currentPage = null, + int? perPage = null, + string? searchTerm = null, + bool includeCurrentPage = true, + bool includePerPage = true, + bool includeSearchTerm = true) + { + return new GetArtistsLiteRequest( + includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, + includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, + includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : 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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestFixture.cs new file mode 100644 index 00000000..1698b9e7 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid request to get the artists of a media library. + /// + /// Optional. The page of results to retrieve. + /// Optional. The maximum number of artists to retrieve per page. + /// Optional. The search term used to filter the artists by name. + /// Whether the current page should be included, or forced to . + /// Whether the per page count should be included, or forced to . + /// Whether the search term should be included, or forced to . + /// The created request to get the artists of a media library. + public GetArtistsRequest Create( + int? currentPage = null, + int? perPage = null, + string? searchTerm = null, + bool includeCurrentPage = true, + bool includePerPage = true, + bool includeSearchTerm = true) + { + return new GetArtistsRequest( + includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, + includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, + includeSearchTerm ? (searchTerm ?? _faker.Name.FullName()) : 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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs new file mode 100644 index 00000000..89389dba --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestFixture.cs @@ -0,0 +1,105 @@ +#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.Tracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistAlbumRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly UpdateArtistTrackRequestFixture _updateArtistTrackRequestFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid request to update an album of an artist. + /// + /// 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 barcode of the album. + /// Optional. The catalog 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 media contributors that performed on the album. + /// Optional. The ratings of the album. + /// Optional. The tracks of the album. + /// 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 barcode should be included, or forced to . + /// Whether the catalog number 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 list should be included, or forced to . + /// Whether the ratings list should be included, or forced to . + /// Whether the tracks list should be included, or forced to . + /// The created request to update an album of an artist. + public UpdateArtistAlbumRequest Create( + Guid? albumId = null, + AlbumMetadataDto? metadata = null, + MusicMediaFormat? mediaFormat = null, + string? barcode = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, + List? tracks = null, + bool includeAlbumId = true, + bool includeMetadata = true, + bool includeMediaFormat = true, + bool includeBarcode = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeTracks = true) + { + return new UpdateArtistAlbumRequest( + includeAlbumId ? (albumId ?? _faker.Random.Guid()) : null, + includeMetadata ? (metadata ?? _albumMetadataDtoFixture.Create()) : null, + includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, + includeCatalogNumber ? (catalogNumber ?? _faker.Random.String2(_faker.Random.Number(1, 50))) : null, + includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? _faker.Random.Guid()) : null, + includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeTracks ? (tracks ?? _updateArtistTrackRequestFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs new file mode 100644 index 00000000..111a76e0 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistRequestFixture +{ + private readonly Faker _faker = new(); + private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + /// + /// Creates a random valid request to update an artist. + /// + /// Optional. The name of the artist. + /// Optional. The website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The media contributors that make up the artist. + /// Optional. The albums of the artist. + /// Whether the name 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 contributors 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, + string? website = null, + Guid? musicBrainzArtistId = null, + List? contributors = null, + List? albums = null, + bool includeName = true, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeContributors = true, + bool includeAlbums = true) + { + return new UpdateArtistRequest( + includeName ? (name ?? _faker.Name.FullName()) : null, + includeWebsite ? (website ?? _faker.Internet.Url()) : null, + includeMusicBrainzArtistId ? (musicBrainzArtistId ?? _faker.Random.Guid()) : null, + includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Int(1, 3))) : null, + includeAlbums ? (albums ?? _updateArtistAlbumRequestFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs new file mode 100644 index 00000000..660c83c9 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestFixture.cs @@ -0,0 +1,133 @@ +#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistTrackRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid request to update a track of an album of an artist. + /// + /// Optional. The Id of the track, when the track already exists. + /// Optional. The file system path of the track. + /// Optional. The audio metadata of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// 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 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. + /// Optional. The ratings of the track. + /// Whether the track Id should be included, or forced to . + /// Whether the path should be included, or forced to . + /// Whether the metadata should be included, or forced to . + /// Whether the track number should be included, or forced to . + /// Whether the disc number 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 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 . + /// Whether the ratings list should be included, or forced to . + /// The created request to update a track of an album of an artist. + public UpdateArtistTrackRequest Create( + Guid? trackId = null, + string? path = null, + AudioMetadataDto? metadata = null, + int? trackNumber = null, + int? discNumber = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + string? work = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + List? moods = null, + List? isrcs = null, + List? contributors = null, + List? ratings = null, + bool includeTrackId = true, + bool includePath = true, + bool includeMetadata = true, + bool includeTrackNumber = true, + bool includeDiscNumber = true, + bool includeScript = true, + bool includeKey = true, + bool includeBpm = true, + bool includeWork = true, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeMusicBrainzWorkId = true, + bool includeMoods = true, + bool includeIsrcs = true, + bool includeContributors = true, + bool includeRatings = true) + { + 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, + 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, + 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, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs new file mode 100644 index 00000000..c45bcafb --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestFixture.cs @@ -0,0 +1,128 @@ +#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class AddTrackRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid request to add a track. + /// + /// Optional. The file system path of the track. + /// Optional. The audio metadata of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// 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 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. + /// Optional. The list of ratings for this track. + /// Whether the path should be included, or forced to . + /// Whether the metadata should be included, or forced to . + /// Whether the track number should be included, or forced to . + /// Whether the disc number 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 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 . + /// Whether the ratings should be included, or forced to . + /// The created request to add a track. + public AddTrackRequest Create( + string? path = null, + AudioMetadataDto? metadata = null, + int? trackNumber = null, + int? discNumber = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + string? work = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + List? moods = null, + List? isrcs = null, + List? contributors = null, + List? ratings = null, + bool includePath = true, + bool includeMetadata = true, + bool includeTrackNumber = true, + bool includeDiscNumber = true, + bool includeScript = true, + bool includeKey = true, + bool includeBpm = true, + bool includeWork = true, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeMusicBrainzWorkId = true, + bool includeMoods = true, + bool includeIsrcs = true, + bool includeContributors = true, + bool includeRatings = true) + { + return new AddTrackRequest( + includePath ? path ?? Path.Combine(Path.GetTempPath(), "lumina-tracks", _faker.System.FileName()) : null, + includeMetadata ? metadata ?? _audioMetadataDtoFixture.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, + 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, + includeRatings ? ratings ?? _audioRatingDtoFixture.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/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs new file mode 100644 index 00000000..f73927dd --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestFixture.cs @@ -0,0 +1,127 @@ +#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +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.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackRequestFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid request to update a track. + /// + /// Optional. The file system path of the track. + /// Optional. The audio metadata of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// 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 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. + /// Optional. The ratings of the track. + /// Whether the disc number 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 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 . + /// Whether the ratings list should be included, or forced to . + /// Whether the path should be included, or forced to . + /// Whether the metadata should be included, or forced to . + /// Whether the track number should be included, or forced to . + /// The created request to update a track. + public UpdateTrackRequest Create( + string? path = null, + AudioMetadataDto? metadata = null, + int? trackNumber = null, + int? discNumber = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + string? work = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + List? moods = null, + List? isrcs = null, + List? contributors = null, + List? ratings = null, + bool includeDiscNumber = true, + bool includeScript = true, + bool includeKey = true, + bool includeBpm = true, + bool includeWork = true, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeMusicBrainzWorkId = true, + bool includeMoods = true, + bool includeIsrcs = true, + bool includeContributors = true, + bool includeRatings = true, + bool includePath = true, + bool includeMetadata = true, + bool includeTrackNumber = true) + { + return new UpdateTrackRequest( + includePath ? (path ?? _faker.System.FilePath()) : null, + includeMetadata ? (metadata ?? _audioMetadataDtoFixture.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, + 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, + includeRatings ? (ratings ?? [.. _audioRatingDtoFixture.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/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs index 54b7f120..6b632386 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; @@ -11,6 +11,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Linq; #endregion @@ -24,13 +25,12 @@ public class AddBookRequestFixture { private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// /// Creates a random valid request to add a book. /// - /// Optional. The Id of the media library the book belongs to. /// Optional. The file system path of the book. /// Optional. The written content metadata of the book. /// Optional. The format of the book. @@ -49,10 +49,23 @@ public class AddBookRequestFixture /// Optional. The ISBNs of the book. /// Optional. The contributors of the book. /// Optional. The ratings of the book. - /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// Whether the format should be included, or forced to . + /// Whether the edition should be included, or forced to . + /// Whether the volume number should be included, or forced to . + /// Whether the ASIN should be included, or forced to . + /// Whether the Goodreads Id should be included, or forced to . + /// Whether the LCCN should be included, or forced to . + /// Whether the OCLC number should be included, or forced to . + /// Whether the Open Library Id should be included, or forced to . + /// Whether the LibraryThing Id should be included, or forced to . + /// Whether the Google Books Id should be included, or forced to . + /// Whether the Barnes and Noble Id should be included, or forced to . + /// Whether the Apple Books Id should be included, or forced to . + /// Whether the ISBNs 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 request to add a book. public AddBookRequest Create( - Guid? libraryId = null, string? path = null, WrittenContentMetadataDto? metadata = null, BookFormat? format = null, @@ -69,13 +82,26 @@ public class AddBookRequestFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null, - bool includeOptionalProperties = true) + bool includeFormat = true, + bool includeEdition = true, + bool includeVolumeNumber = true, + bool includeAsin = true, + bool includeGoodreadsId = true, + bool includeLccn = true, + bool includeOclcNumber = true, + bool includeOpenLibraryId = true, + bool includeLibraryThingId = true, + bool includeGoogleBooksId = true, + bool includeBarnesAndNobleId = true, + bool includeAppleBooksId = true, + bool includeIsbns = true, + bool includeRatings = true, + bool includeContributors = true) { return new Faker() .CustomInstantiator(f => new AddBookRequest( - default, default!, default!, default, @@ -95,25 +121,24 @@ public class AddBookRequestFixture default!, default! )) - .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) - .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Path, f => path ?? Path.Combine(Path.GetTempPath(), "lumina-books", f.System.FileName())) .RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create()) - .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) - .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Format, f => format ?? (includeFormat ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeEdition ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeVolumeNumber ? (float?)f.Random.Number(1, 3) : null)) .RuleFor(x => x.Series, series) - .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) - .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) - .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) - .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) - .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) - .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) - .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) - .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) - .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + .RuleFor(x => x.ASIN, f => asin ?? (includeAsin ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeGoodreadsId ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeLccn ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOclcNumber ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOpenLibraryId ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeLibraryThingId ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeGoogleBooksId ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeBarnesAndNobleId ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeAppleBooksId ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeIsbns ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeRatings ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeContributors ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs deleted file mode 100644 index 92ed937f..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class GetBookRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The unique identifier of the book to retrieve. - /// The created . - public GetBookRequest Create( - string? id = null) - { - return new GetBookRequest(id ?? Guid.NewGuid().ToString()); - } - - /// - /// 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/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs index d532e90d..c351b00d 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs @@ -2,7 +2,6 @@ using Bogus; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -21,7 +20,6 @@ public class GetBooksLiteRequestFixture /// /// Creates a with default or random values. /// - /// Optional. The Id of the media library whose books are retrieved. /// Optional. The page of results to retrieve. /// Optional. The maximum number of books to retrieve per page. /// Optional. The search term used to filter results. @@ -33,7 +31,6 @@ public class GetBooksLiteRequestFixture /// Whether the per page count should be included, or forced to . /// The created . public GetBooksLiteRequest Create( - Guid? libraryId = null, int? currentPage = null, int? perPage = null, string? searchTerm = null, @@ -45,7 +42,6 @@ public class GetBooksLiteRequestFixture bool includePerPage = true) { return new GetBooksLiteRequest( - LibraryId: libraryId ?? _faker.Random.Guid(), CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, SearchTerm: searchTerm ?? _faker.Lorem.Word(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs index db6b9fe0..6ec5c577 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestFixture.cs @@ -2,7 +2,6 @@ using Bogus; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -21,7 +20,6 @@ public class GetBooksRequestFixture /// /// Creates a with default or random values. /// - /// Optional. The Id of the media library whose books are retrieved. /// Optional. The page of results to retrieve. /// Optional. The maximum number of books to retrieve per page. /// Optional. The search term used to filter results. @@ -31,7 +29,6 @@ public class GetBooksRequestFixture /// Whether the per page count should be included, or forced to . /// The created . public GetBooksRequest Create( - Guid? libraryId = null, int? currentPage = null, int? perPage = null, string? searchTerm = null, @@ -41,7 +38,6 @@ public class GetBooksRequestFixture bool includePerPage = true) { return new GetBooksRequest( - LibraryId: libraryId ?? _faker.Random.Guid(), CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Number(1, 100)) : null, PerPage: includePerPage ? (perPage ?? _faker.Random.Number(1, 200)) : null, SearchTerm: searchTerm ?? _faker.Lorem.Word(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestFixture.cs deleted file mode 100644 index 5fcc33f8..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingAvailabilityRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the book whose reading availability is checked. - /// The created . - public GetReadingAvailabilityRequest Create( - Guid? bookId = null) - { - return new GetReadingAvailabilityRequest(bookId ?? Guid.NewGuid()); - } - - /// - /// 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/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestFixture.cs deleted file mode 100644 index b93b4097..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingManifestRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the book whose reading manifest is retrieved. - /// The created . - public GetReadingManifestRequest Create( - Guid? bookId = null) - { - return new GetReadingManifestRequest(bookId ?? Guid.NewGuid()); - } - - /// - /// 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/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestFixture.cs deleted file mode 100644 index d38695f1..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingResourceRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the book whose resource is retrieved. - /// Optional. The opaque resource key of the resource. - /// The created . - public GetReadingResourceRequest Create( - Guid? bookId = null, - string? resourceKey = null) - { - return new GetReadingResourceRequest(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}"); - } - - /// - /// 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/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestFixture.cs deleted file mode 100644 index a60b9dc0..00000000 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Fixture class for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingSectionRequestFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The Id of the book whose reading section is retrieved. - /// Optional. The opaque location reference of the reading section. - /// The created . - public GetReadingSectionRequest Create( - Guid? bookId = null, - string? locationRef = null) - { - return new GetReadingSectionRequest(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}"); - } - - /// - /// 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/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs index f71ecc3f..9b5047d0 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; @@ -24,13 +24,12 @@ public class UpdateBookRequestFixture { private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); /// /// Creates a random valid request to update a book. /// - /// Optional. The Id of the book to update. /// Optional. The written content metadata of the book. /// Optional. The format of the book. /// Optional. The edition of the book. @@ -48,12 +47,23 @@ public class UpdateBookRequestFixture /// Optional. The ISBNs of the book. /// Optional. The contributors of the book. /// Optional. The ratings of the book. - /// Whether the properties that are not explicitly provided should be randomized, or forced to . - /// Optional. The raw string value of the Id of the book to update. Takes precedence over . - /// Whether the Id should be included, or forced to . + /// Whether the format should be included, or forced to . + /// Whether the edition should be included, or forced to . + /// Whether the volume number should be included, or forced to . + /// Whether the ASIN should be included, or forced to . + /// Whether the Goodreads Id should be included, or forced to . + /// Whether the LCCN should be included, or forced to . + /// Whether the OCLC number should be included, or forced to . + /// Whether the Open Library Id should be included, or forced to . + /// Whether the LibraryThing Id should be included, or forced to . + /// Whether the Google Books Id should be included, or forced to . + /// Whether the Barnes and Noble Id should be included, or forced to . + /// Whether the Apple Books Id should be included, or forced to . + /// Whether the ISBNs 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 request to update a book. public UpdateBookRequest Create( - Guid? id = null, WrittenContentMetadataDto? metadata = null, BookFormat? format = null, string? edition = null, @@ -69,15 +79,26 @@ public class UpdateBookRequestFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null, - bool includeOptionalProperties = true, - string? rawId = null, - bool includeId = true) + bool includeFormat = true, + bool includeEdition = true, + bool includeVolumeNumber = true, + bool includeAsin = true, + bool includeGoodreadsId = true, + bool includeLccn = true, + bool includeOclcNumber = true, + bool includeOpenLibraryId = true, + bool includeLibraryThingId = true, + bool includeGoogleBooksId = true, + bool includeBarnesAndNobleId = true, + bool includeAppleBooksId = true, + bool includeIsbns = true, + bool includeRatings = true, + bool includeContributors = true) { return new Faker() .CustomInstantiator(f => new UpdateBookRequest( - default, default!, default, default, @@ -96,24 +117,23 @@ public class UpdateBookRequestFixture default!, default! )) - .RuleFor(x => x.Id, f => includeId ? (rawId ?? id?.ToString() ?? Guid.NewGuid().ToString()) : null) .RuleFor(x => x.Metadata, metadata ?? _writtenContentMetadataDtoFixture.Create()) - .RuleFor(x => x.Format, f => format ?? (includeOptionalProperties ? f.PickRandom() : null)) - .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeOptionalProperties ? (float?)f.Random.Number(1, 3) : null)) + .RuleFor(x => x.Format, f => format ?? (includeFormat ? f.PickRandom() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeEdition ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, f => volumeNumber ?? (includeVolumeNumber ? (float?)f.Random.Number(1, 3) : null)) .RuleFor(x => x.Series, series) - .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) - .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeOptionalProperties ? f.Random.Number(100000, 500000).ToString() : null)) - .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) - .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) - .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) - .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) - .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) - .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) - .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) - .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) - .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); + .RuleFor(x => x.ASIN, f => asin ?? (includeAsin ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, f => goodreadsId ?? (includeGoodreadsId ? f.Random.Number(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeLccn ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOclcNumber ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOpenLibraryId ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeLibraryThingId ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeGoogleBooksId ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeBarnesAndNobleId ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeAppleBooksId ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeIsbns ? [.. _isbnDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeRatings ? [.. _bookRatingDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeContributors ? [.. _mediaContributorReferenceDtoFixture.CreateMany(f.Random.Number(1, 3))] : null)); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponseFixture.cs new file mode 100644 index 00000000..5fc48178 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponseFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AlbumLiteResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the album. + /// Optional. The title of the album. + /// Optional. The number of tracks of the release. + /// The created . + public AlbumLiteResponse Create( + Guid? id = null, + string? title = null, + int? totalTracks = null) + { + return new AlbumLiteResponse( + id ?? Guid.NewGuid(), + title ?? _faker.Commerce.ProductName(), + totalTracks ?? _faker.Random.Int(1, 30)); + } + + /// + /// 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/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs new file mode 100644 index 00000000..22ea8889 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponseFixture.cs @@ -0,0 +1,116 @@ +#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.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AlbumResponseFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly TrackResponseFixture _trackResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the album. + /// Optional. The Id of the artist the album belongs to. + /// 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 barcode of the album. + /// Optional. The catalog 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 date and time when the album was created. + /// Optional. The date and time when the album was updated. + /// Optional. The list of contributor references of the album. + /// 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 barcode should be included, or forced to . + /// Whether the catalog number 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 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 tracks should be included, or forced to . + /// The created . + public AlbumResponse Create( + Guid? id = null, + Guid? artistId = null, + Guid? libraryId = null, + AlbumMetadataDto? metadata = null, + MusicMediaFormat? mediaFormat = null, + string? barcode = null, + string? catalogNumber = null, + Guid? musicBrainzReleaseId = null, + Guid? musicBrainzReleaseGroupId = null, + Guid? musicBrainzReleaseArtistId = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + List? contributors = null, + List? ratings = null, + List? tracks = null, + bool includeMediaFormat = true, + bool includeBarcode = true, + bool includeCatalogNumber = true, + bool includeMusicBrainzReleaseId = true, + bool includeMusicBrainzReleaseGroupId = true, + bool includeMusicBrainzReleaseArtistId = true, + bool includeUpdatedOnUtc = true, + bool includeContributors = true, + bool includeRatings = true, + bool includeTracks = true) + { + return new AlbumResponse( + id ?? Guid.NewGuid(), + artistId ?? Guid.NewGuid(), + libraryId ?? Guid.NewGuid(), + metadata ?? _albumMetadataDtoFixture.Create(), + includeMediaFormat ? (mediaFormat ?? _faker.PickRandom()) : null, + includeBarcode ? (barcode ?? _faker.Random.String2(13, "0123456789")) : null, + includeCatalogNumber ? (catalogNumber ?? _faker.Random.AlphaNumeric(10)) : null, + includeMusicBrainzReleaseId ? (musicBrainzReleaseId ?? Guid.NewGuid()) : null, + includeMusicBrainzReleaseGroupId ? (musicBrainzReleaseGroupId ?? Guid.NewGuid()) : null, + includeMusicBrainzReleaseArtistId ? (musicBrainzReleaseArtistId ?? Guid.NewGuid()) : null, + createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), + includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : null, + includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null, + includeRatings ? (ratings ?? _audioRatingDtoFixture.CreateMany(1)) : null, + includeTracks ? (tracks ?? _trackResponseFixture.CreateMany(1)) : 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/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponseFixture.cs new file mode 100644 index 00000000..5bbde1f8 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponseFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistLiteResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the artist. + /// Optional. The name of the artist. + /// The created . + public ArtistLiteResponse Create( + Guid? id = null, + string? name = null) + { + return new ArtistLiteResponse( + id ?? Guid.NewGuid(), + name ?? _faker.Name.FullName()); + } + + /// + /// 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/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs new file mode 100644 index 00000000..c8e4178b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponseFixture.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +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; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtistResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AlbumResponseFixture _albumResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// 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 website of the artist. + /// Optional. The MusicBrainz identifier of the artist. + /// Optional. The list of contributor references 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 update date should be included, or forced to . + /// Whether the contributors 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, + string? website = null, + Guid? musicBrainzArtistId = null, + List? contributors = null, + List? albums = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + bool includeWebsite = true, + bool includeMusicBrainzArtistId = true, + bool includeUpdatedOnUtc = true, + bool includeContributors = true, + bool includeAlbums = true) + { + return new ArtistResponse( + id ?? Guid.NewGuid(), + libraryId ?? Guid.NewGuid(), + name ?? _faker.Name.FullName(), + includeWebsite ? (website ?? _faker.Internet.Url()) : null, + includeMusicBrainzArtistId ? (musicBrainzArtistId ?? Guid.NewGuid()) : null, + includeContributors ? (contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1)) : null, + includeAlbums ? (albums ?? _albumResponseFixture.CreateMany(1)) : null, + createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), + includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent().ToUniversalTime()) : 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/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponseFixture.cs new file mode 100644 index 00000000..4118f4ec --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponseFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackLiteResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the track. + /// 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. + /// Whether the disc number should be included, or forced to . + /// The created . + public TrackLiteResponse Create( + Guid? id = null, + string? title = null, + int? trackNumber = null, + int? discNumber = null, + bool includeDiscNumber = true) + { + return new TrackLiteResponse( + id ?? _faker.Random.Guid(), + title ?? _faker.Lorem.Sentence(), + trackNumber ?? _faker.Random.Int(1, 30), + includeDiscNumber ? (discNumber ?? _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/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs new file mode 100644 index 00000000..2c009ff5 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponseFixture.cs @@ -0,0 +1,118 @@ +#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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackResponseFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the track. + /// Optional. The Id of the album the track belongs to. + /// Optional. The Id of the media library this track belongs to. + /// Optional. The file system path of the track. + /// Optional. The audio metadata of the track. + /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. + /// 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 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. + /// Optional. The list of ISRCs of the track. + /// Optional. The list of contributor references of the track. + /// 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, + int? trackNumber = null, + int? discNumber = null, + string? script = null, + MusicKey? key = null, + int? bpm = null, + string? work = null, + Guid? musicBrainzRecordingId = null, + Guid? musicBrainzTrackId = null, + Guid? musicBrainzWorkId = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + List? moods = null, + List? isrcs = null, + List? contributors = null, + List? ratings = null, + bool includeMusicBrainzRecordingId = true, + bool includeMusicBrainzTrackId = true, + bool includeMusicBrainzWorkId = true) + { + return new TrackResponse( + id ?? Guid.NewGuid(), + albumId ?? Guid.NewGuid(), + libraryId ?? Guid.NewGuid(), + path ?? _faker.System.FilePath(), + metadata ?? _audioMetadataDtoFixture.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), + 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), + isrcs ?? _isrcDtoFixture.CreateMany(1), + contributors ?? _mediaContributorReferenceDtoFixture.CreateMany(1), + ratings ?? _audioRatingDtoFixture.CreateMany(1)); + } + + /// + /// 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/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs index b07e8c9c..7226bbf4 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 @@ -24,7 +24,7 @@ public class BookResponseFixture private readonly Faker _faker = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new(); @@ -70,7 +70,7 @@ public class BookResponseFixture _faker.Random.AlphaNumeric(10), _faker.Random.AlphaNumeric(8), _isbnDtoFixture.CreateMany(1), - _mediaContributorDtoFixture.CreateMany(1), + _mediaContributorReferenceDtoFixture.CreateMany(1), _bookRatingDtoFixture.CreateMany(1), metadataStatus ?? _faker.PickRandom(), _faker.Date.Recent().ToUniversalTime(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseFixture.cs new file mode 100644 index 00000000..bbed6117 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The relative path of the stored cover image. + /// The created . + public UpdateBookCoverResponse Create(string? coverPath = null) + { + return new UpdateBookCoverResponse( + coverPath ?? _faker.System.FilePath() + ); + } + + /// + /// 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/Themes/ThemeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs index 5913454b..dddf632f 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Themes/ThemeResponseFixture.cs @@ -28,12 +28,12 @@ public class ThemeResponseFixture /// Optional. The author of the theme. /// Optional. The version of the theme. /// Optional. The preview image path of the theme, or when the theme has no preview. - /// Whether the preview path should be included, or forced to . /// Optional. The source the theme was installed from. /// Optional. Whether the theme is the currently active one. - /// Whether the currently active flag should be included, or forced to . /// Optional. The UTC timestamp when the theme was installed. /// Optional. Whether the theme was deleted by the user. + /// Whether the preview path should be included, or forced to . + /// Whether the currently active flag should be included, or forced to . /// The created . public ThemeResponse Create( Guid? id = null, @@ -43,12 +43,12 @@ public class ThemeResponseFixture string? author = null, string? version = null, string? previewPath = null, - bool includePreviewPath = false, ThemeInstallSource? installSource = null, bool? isCurrent = null, - bool includeIsCurrent = false, DateTime? installedAtUtc = null, - bool? isDeleted = null) + bool? isDeleted = null, + bool includePreviewPath = false, + bool includeIsCurrent = false) { return new ThemeResponse( id ?? Guid.NewGuid(), diff --git a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs index 0a9640c7..3f7657a4 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs @@ -2,7 +2,6 @@ using Bogus; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -32,14 +31,10 @@ public class LanguageInfoFixture { string[] languages = ["en", "es", "fr", "de", "it", "ja", "ko", "zh", "pt", "ru"]; - Result languageInfoResult = LanguageInfo.Create( + return LanguageInfo.Create( languageCode ?? _faker.PickRandom(languages), languageName ?? _faker.Lorem.Word(), nativeName ?? Optional.Some(_faker.Lorem.Word())); - - if (languageInfoResult.IsFailure) - throw new InvalidOperationException("Failed to create LanguageInfo: " + string.Join(", ", languageInfoResult.Errors)); - return languageInfoResult.Value; } /// diff --git a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/MoodFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/MoodFixture.cs new file mode 100644 index 00000000..3d56c4ed --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/MoodFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MoodFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the mood. If not provided, a random name is generated. + /// The created . + public Mood Create( + string? name = null) + { + Result moodResult = Mood.Create(name ?? _faker.Lorem.Word()); + + if (moodResult.IsFailure) + throw new InvalidOperationException("Failed to create Mood: " + string.Join(", ", moodResult.Errors)); + return moodResult.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/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs index 1fa1db57..2a2f7d6a 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs @@ -18,7 +18,6 @@ namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; public class ReleaseInfoFixture { private readonly Faker _faker = new(); - private readonly Random _random = new(); /// /// Creates a random valid . @@ -38,12 +37,26 @@ public class ReleaseInfoFixture Optional? releaseCountry = null, Optional? releaseVersion = null) { - int generatedYear = _random.Next(1900, 2000); + Optional resolvedReReleaseDate = reReleaseDate ?? Optional.None(); + Optional resolvedReReleaseYear = reReleaseYear ?? Optional.None(); + if (resolvedReReleaseDate.HasValue && !resolvedReReleaseYear.HasValue) + resolvedReReleaseYear = Optional.Some(resolvedReReleaseDate.Value.Year); + else if (!resolvedReReleaseDate.HasValue && resolvedReReleaseYear.HasValue) + resolvedReReleaseDate = Optional.Some(new DateOnly(resolvedReReleaseYear.Value, 1, 1)); Optional resolvedOriginalDate = originalReleaseDate ?? Optional.None(); Optional resolvedOriginalYear = originalReleaseYear ?? Optional.None(); if (!resolvedOriginalDate.HasValue && !resolvedOriginalYear.HasValue) { + // The generated original year must never exceed the re-release year, otherwise the domain invariant is violated. + int lowerBound = 1900; + int upperBoundExclusive = 2000; + if (resolvedReReleaseYear.HasValue) + { + lowerBound = Math.Min(lowerBound, resolvedReReleaseYear.Value); + upperBoundExclusive = Math.Min(upperBoundExclusive, resolvedReReleaseYear.Value + 1); + } + int generatedYear = Random.Shared.Next(lowerBound, Math.Max(upperBoundExclusive, lowerBound + 1)); resolvedOriginalDate = Optional.Some(new DateOnly(generatedYear, 1, 1)); resolvedOriginalYear = Optional.Some(generatedYear); } @@ -52,14 +65,7 @@ public class ReleaseInfoFixture else if (!resolvedOriginalYear.HasValue) resolvedOriginalYear = Optional.Some(resolvedOriginalDate.Value.Year); - Optional resolvedReReleaseDate = reReleaseDate ?? Optional.None(); - Optional resolvedReReleaseYear = reReleaseYear ?? Optional.None(); - if (resolvedReReleaseDate.HasValue && !resolvedReReleaseYear.HasValue) - resolvedReReleaseYear = Optional.Some(resolvedReReleaseDate.Value.Year); - else if (!resolvedReReleaseDate.HasValue && resolvedReReleaseYear.HasValue) - resolvedReReleaseDate = Optional.Some(new DateOnly(resolvedReReleaseYear.Value, 1, 1)); - - Optional resolvedReleaseCountry = releaseCountry ?? Optional.Some(Enum.GetValues()[_random.Next(Enum.GetValues().Length)]); + Optional resolvedReleaseCountry = releaseCountry ?? Optional.Some(Enum.GetValues()[Random.Shared.Next(Enum.GetValues().Length)]); Result releaseInfoResult = ReleaseInfo.Create( resolvedOriginalDate, diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRatingFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRatingFixture.cs new file mode 100644 index 00000000..065feee1 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRatingFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The numeric value of the rating. + /// Optional. The maximum possible rating value. + /// Optional. The source of the rating. + /// Optional. The number of votes or reviews. + /// The created . + public AudioRating Create( + decimal? value = null, + decimal? maxValue = null, + Optional? source = null, + Optional? voteCount = null) + { + decimal resolvedMaxValue = maxValue ?? 5m; + Result ratingResult = AudioRating.Create( + value ?? _faker.Random.Decimal(0m, resolvedMaxValue), + resolvedMaxValue, + source ?? Optional.Some(_faker.PickRandom()), + voteCount ?? Optional.Some(_faker.Random.Int(0, 10000))); + + if (ratingResult.IsFailure) + throw new InvalidOperationException("Failed to create AudioRating: " + string.Join(", ", ratingResult.Errors)); + return ratingResult.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/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs new file mode 100644 index 00000000..6c434ed6 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the library Id. + /// The created . + public LibraryId Create( + Guid? value = null) + { + return value is null ? LibraryId.CreateUnique() : LibraryId.Create(value.Value); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorIdFixture.cs new file mode 100644 index 00000000..4afa0f55 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the media contributor Id. + /// The created . + public MediaContributorId Create( + Guid? value = null) + { + return value is null ? MediaContributorId.CreateUnique() : MediaContributorId.Create(value.Value); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs new file mode 100644 index 00000000..5182b00c --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistFixture.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +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.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 System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; + +/// +/// Fixture class for the domain aggregate root. +/// +[ExcludeFromCodeCoverage] +public class ArtistFixture +{ + 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(); + + /// + /// 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 website of the artist. + /// Optional. The MusicBrainz identifier 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? website = null, + Optional? musicBrainzArtistId = null, + List? contributors = null, + List? albums = null) + { + Result artistResult = Artist.Create( + libraryId ?? _libraryIdFixture.Create(), + name ?? _faker.Name.FullName(), + website ?? Optional.Some(_faker.Internet.Url()), + musicBrainzArtistId ?? Optional.Some(_musicBrainzIdFixture.Create()), + contributors ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(_ => _musicMediaContributorFixture.Create())], + albums ?? [_albumFixture.Create()]); + + if (artistResult.IsFailure) + throw new InvalidOperationException("Failed to create Artist: " + string.Join(", ", artistResult.Errors)); + return artistResult.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/Entities/AlbumFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumFixture.cs new file mode 100644 index 00000000..d161f7b0 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumFixture.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +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; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; + +/// +/// Fixture class for the domain entity. +/// +[ExcludeFromCodeCoverage] +public class AlbumFixture +{ + private readonly Faker _faker = new(); + private readonly AlbumMetadataFixture _albumMetadataFixture = new(); + private readonly BarcodeFixture _barcodeFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); + + /// + /// Creates a random valid domain entity. + /// + /// Optional. The album metadata of the album. + /// Optional. The physical or digital medium of the album. + /// Optional. The barcode of the album. + /// Optional. The catalog 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 media contributors of the album. + /// Optional. The ratings of the album. + /// Optional. The tracks of the album. Defaults to an empty list so callers can control the initial tracks. + /// The created domain entity. + public Album Create( + AlbumMetadata? metadata = null, + Optional? mediaFormat = null, + Optional? barcode = null, + Optional? catalogNumber = null, + Optional? musicBrainzReleaseId = null, + Optional? musicBrainzReleaseGroupId = null, + Optional? musicBrainzReleaseArtistId = null, + List? contributors = null, + List? ratings = null, + List? tracks = null) + { + Result albumResult = Album.Create( + metadata ?? _albumMetadataFixture.Create(), + mediaFormat ?? Optional.Some(_faker.PickRandom()), + barcode ?? Optional.Some(_barcodeFixture.Create()), + catalogNumber ?? Optional.Some(_faker.Random.String2(_faker.Random.Int(5, 20))), + musicBrainzReleaseId ?? Optional.Some(_musicBrainzIdFixture.Create()), + musicBrainzReleaseGroupId ?? Optional.Some(_musicBrainzIdFixture.Create()), + musicBrainzReleaseArtistId ?? 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())], + tracks ?? []); + + if (albumResult.IsFailure) + throw new InvalidOperationException("Failed to create Album: " + string.Join(", ", albumResult.Errors)); + return albumResult.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/Entities/TrackFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackFixture.cs new file mode 100644 index 00000000..6432d8ed --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackFixture.cs @@ -0,0 +1,101 @@ +#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.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.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; + +/// +/// Fixture class for the domain entity. +/// +[ExcludeFromCodeCoverage] +public class TrackFixture +{ + private readonly Faker _faker = new(); + private readonly AudioMetadataFixture _audioMetadataFixture = new(); + private readonly MoodFixture _moodFixture = new(); + private readonly IsrcFixture _isrcFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); + + /// + /// Creates a random valid domain entity. + /// + /// Optional. The file system path of the track. + /// Optional. The audio metadata 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. The ISRCs of the track. + /// Optional. The title of 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, + int? trackNumber = null, + Optional? discNumber = null, + List? moods = null, + Optional? script = null, + Optional? key = null, + Optional? bpm = null, + List? isrcs = 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(), + 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)), + isrcs ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 2)).Select(_ => _isrcFixture.Create())], + work ?? Optional.Some(_faker.Lorem.Sentence()), + 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())]); + + if (trackResult.IsFailure) + throw new InvalidOperationException("Failed to create Track: " + string.Join(", ", trackResult.Errors)); + return trackResult.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/AlbumIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumIdFixture.cs new file mode 100644 index 00000000..274bc29c --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +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 AlbumIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public AlbumId Create(Guid? value = null) + { + return value is null ? AlbumId.CreateUnique() : AlbumId.Create(value.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/AlbumMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataFixture.cs new file mode 100644 index 00000000..b3776200 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataFixture.cs @@ -0,0 +1,86 @@ +#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 Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +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 AlbumMetadataFixture +{ + private readonly Faker _faker = new(); + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the album. + /// Optional. The original title 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 status of the release. + /// Optional. The number of discs of the release. + /// Optional. The number of tracks of the release. + /// The created . + public AlbumMetadata Create( + string? title = null, + Optional? originalTitle = null, + Optional? description = null, + ReleaseInfo? releaseInfo = null, + List? genres = null, + List? tags = null, + Optional? language = null, + Optional? originalLanguage = null, + Optional? releaseType = null, + Optional? releaseStatus = null, + Optional? totalDiscs = null, + int? totalTracks = null) + { + Result metadataResult = AlbumMetadata.Create( + title ?? _faker.Commerce.ProductName(), + originalTitle ?? Optional.None(), + 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()), + releaseStatus ?? Optional.Some(_faker.PickRandom()), + totalDiscs ?? Optional.Some(_faker.Random.Int(1, 4)), + totalTracks ?? _faker.Random.Int(1, 50)); + + if (metadataResult.IsFailure) + throw new InvalidOperationException("Failed to create AlbumMetadata: " + string.Join(", ", metadataResult.Errors)); + return metadataResult.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/ArtistIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdFixture.cs new file mode 100644 index 00000000..ee1e8a03 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +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 ArtistIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public ArtistId Create( + Guid? value = null) + { + return value is null ? ArtistId.CreateUnique() : ArtistId.Create(value.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/BarcodeFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/BarcodeFixture.cs new file mode 100644 index 00000000..e2c109b4 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/BarcodeFixture.cs @@ -0,0 +1,55 @@ +#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 BarcodeFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the barcode. If not provided, a random valid barcode is generated. + /// The created . + public Barcode Create( + string? value = null) + { + Result barcodeResult = Barcode.Create(value ?? GenerateRandomValue()); + + if (barcodeResult.IsFailure) + throw new InvalidOperationException("Failed to create Barcode: " + string.Join(", ", barcodeResult.Errors)); + return barcodeResult.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())]; + } + + /// + /// Generates a random value matching the ^\d{12,13}$ barcode format. + /// + /// The generated barcode value. + private string GenerateRandomValue() + { + int digitCount = _faker.Random.Int(12, 13); + return _faker.Random.String2(digitCount, "0123456789"); + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/IsrcFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/IsrcFixture.cs new file mode 100644 index 00000000..81949271 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/IsrcFixture.cs @@ -0,0 +1,57 @@ +#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 IsrcFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The value of the ISRC. If not provided, a random valid ISRC is generated. + /// The created . + public Isrc Create( + string? value = null) + { + Result isrcResult = Isrc.Create(value ?? GenerateRandomValue()); + + if (isrcResult.IsFailure) + throw new InvalidOperationException("Failed to create Isrc: " + string.Join(", ", isrcResult.Errors)); + return isrcResult.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())]; + } + + /// + /// Generates a random value matching the ^[A-Z]{2}[A-Z0-9]{3}[0-9]{7}$ ISRC format. + /// + /// The generated ISRC value. + private string GenerateRandomValue() + { + string countryCode = _faker.Random.String2(2, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + string registrantCode = _faker.Random.String2(3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + string yearAndDesignationCode = _faker.Random.Number(1000000, 9999999).ToString(); + return countryCode + registrantCode + yearAndDesignationCode; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzIdFixture.cs new file mode 100644 index 00000000..37c515ef --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +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 MusicBrainzIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public MusicBrainzId Create( + Guid? value = null) + { + return MusicBrainzId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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/MusicMediaContributorFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributorFixture.cs new file mode 100644 index 00000000..c0d30c86 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributorFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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 MusicMediaContributorFixture +{ + private readonly Faker _faker = new(); + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier of the media contributor. + /// Optional. The role the contributor played. + /// The created . + public MusicMediaContributor Create( + MediaContributorId? contributorId = null, + MediaContributorRole? role = null) + { + Result contributorResult = MusicMediaContributor.Create( + contributorId ?? _mediaContributorIdFixture.Create(), + role ?? _faker.PickRandom()); + + if (contributorResult.IsFailure) + throw new InvalidOperationException("Failed to create MusicMediaContributor: " + string.Join(", ", contributorResult.Errors)); + return contributorResult.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/TrackIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/TrackIdFixture.cs new file mode 100644 index 00000000..77e50b7d --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/TrackIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +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 TrackIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public TrackId Create( + Guid? value = null) + { + return value is null ? TrackId.CreateUnique() : TrackId.Create(value.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 c786875c..9dfa2bee 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 @@ -23,7 +23,6 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedCo public class LibraryFixture { private readonly Faker _faker = new(); - private readonly Random _random = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly ScanIdFixture _scanIdFixture = new(); @@ -37,13 +36,13 @@ public class LibraryFixture /// Optional. The library type. /// Optional. The content locations of the library. /// Optional. The cover image of the library. - /// Whether the cover image should be included, or forced to . /// Whether the library is enabled. /// Whether the library is locked. /// Whether metadata download from the web is enabled. /// 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. + /// Whether the cover image should be included, or left unset, meaning the library has no cover. /// The created . public Library Create( Guid? id = null, @@ -52,13 +51,13 @@ public class LibraryFixture LibraryType? libraryType = null, IEnumerable? contentLocations = null, string? coverImage = null, - bool includeCoverImage = true, bool isEnabled = true, bool isLocked = false, bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = false, bool shouldSkipUnchangedDirectoriesDuringScan = false, - IEnumerable? scanIds = null) + IEnumerable? scanIds = null, + bool includeCoverImage = true) { List validPaths = [ @@ -77,8 +76,8 @@ public class LibraryFixture resolvedUserId, title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? _faker.PickRandom(), - contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), - resolvedCoverImage, + contentLocations ?? validPaths.Take(Random.Shared.Next(1, validPaths.Count)), + Optional.FromNullable(resolvedCoverImage), isEnabled, isLocked, canDownloadMetadataFromWeb, @@ -91,8 +90,8 @@ public class LibraryFixture resolvedUserId, title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? _faker.PickRandom(), - contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), - resolvedCoverImage, + contentLocations ?? validPaths.Take(Random.Shared.Next(1, validPaths.Count)), + Optional.FromNullable(resolvedCoverImage), isEnabled, isLocked, canDownloadMetadataFromWeb, diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs index b99dd4cd..340d81f9 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventFixture.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; +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; @@ -44,6 +45,6 @@ public class LibraryScanFailedDomainEventFixture libraryId ?? _libraryIdFixture.Create(), mediaLibraryScanCompositeId ?? _mediaLibraryScanCompositeIdFixture.Create(), occurredOnUtc ?? DateTime.UtcNow, - includeErrorMessage ? (errorMessage ?? _faker.Random.Words()) : null); + Optional.FromNullable(includeErrorMessage ? (errorMessage ?? _faker.Random.Words()) : null)); } } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs deleted file mode 100644 index cd3744d6..00000000 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs +++ /dev/null @@ -1,42 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Bogus; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; - -/// -/// Fixture class for the domain value object. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorRoleFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a random valid . - /// - /// Optional. The name of the role. If not provided, a random name is generated. - /// Optional. The category of the role. If not provided, a random category is generated. - /// The created . - public MediaContributorRole Create(string? name = null, MediaContributorRoleCategory? category = null) - { - return MediaContributorRole.Create( - name ?? _faker.Lorem.Word(), - category ?? _faker.PickRandom()).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/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs index 331d81b0..b230dda2 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -27,7 +27,6 @@ public class BookFixture private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new(); private readonly IsbnFixture _isbnFixture = new(); private readonly BookRatingFixture _bookRatingFixture = new(); - private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); /// /// Creates a random valid domain aggregate. @@ -70,7 +69,7 @@ public class BookFixture string? barnesAndNobleId = null, string? appleBooksId = null, List? isbns = null, - List? contributors = null, + List? contributors = null, List? ratings = null) { return Book.Create( @@ -91,7 +90,7 @@ public class BookFixture barnesAndNobleId is null ? Optional.Some(_faker.Random.String2(10, "0123456789")) : Optional.Some(barnesAndNobleId), appleBooksId is null ? Optional.Some($"id{_faker.Random.Number(1, 999999)}") : Optional.Some(appleBooksId), isbns ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _isbnFixture.Create())], - contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _mediaContributorIdFixture.Create())], + contributors ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => BookMediaContributor.Create(MediaContributorId.CreateUnique(), MediaContributorRole.Author).Value)], ratings ?? [.. Enumerable.Range(0, _faker.Random.Number(1, 4)).Select(_ => _bookRatingFixture.Create())] ).Value; } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs deleted file mode 100644 index e8293a8b..00000000 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs +++ /dev/null @@ -1,37 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#endregion - -namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; - -/// -/// Fixture class for the domain value object. -/// -[ExcludeFromCodeCoverage] -public class BookLibraryIdFixture -{ - /// - /// Creates a random valid . - /// - /// Optional. The value used to create the . If not provided, a random value is generated. - /// The created . - public BookLibraryId Create(Guid? value = null) - { - return value is null ? BookLibraryId.CreateUnique().Value : BookLibraryId.Create(value.Value).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/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs index 0305ecd6..c8b4bbb6 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingFixture.cs @@ -17,7 +17,6 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBound public class BookRatingFixture { private readonly Fixture _fixture = new(); - private readonly Random _random = new(); /// /// Creates a random valid . @@ -33,10 +32,10 @@ public class BookRatingFixture Optional? source = null, Optional? voteCount = null) { - maxValue ??= _random.Next(5, 10); - value ??= _random.Next(1, (int)maxValue.Value); + maxValue ??= Random.Shared.Next(5, 10); + value ??= Random.Shared.Next(1, (int)maxValue.Value); source ??= Optional.Some(_fixture.Create()); - voteCount ??= Optional.Some(_random.Next(1, 1000)); + voteCount ??= Optional.Some(Random.Shared.Next(1, 1000)); return BookRating.Create(value.Value, maxValue.Value, source.Value, voteCount.Value).Value; } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs index 674e4d1b..ef09dd80 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs @@ -15,7 +15,6 @@ namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBound [ExcludeFromCodeCoverage] public class IsbnFixture { - private readonly Random _random = new(); /// /// Creates a valid with a random or explicitly requested format. @@ -34,7 +33,7 @@ public class IsbnFixture return result.Value; } - IsbnFormat requestedFormat = format ?? (_random.Next(2) == 0 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13); + IsbnFormat requestedFormat = format ?? (Random.Shared.Next(2) == 0 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13); string isbn = requestedFormat == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13(); return Isbn.Create(isbn, requestedFormat).Value; } @@ -56,7 +55,7 @@ public class IsbnFixture { int[] digits = new int[9]; for (int i = 0; i < 9; i++) - digits[i] = _random.Next(0, 10); + digits[i] = Random.Shared.Next(0, 10); int sum = 0; for (int i = 0; i < 9; i++) @@ -70,10 +69,10 @@ public class IsbnFixture private string GenerateValidIsbn13() { - string prefix = _random.Next(2) == 0 ? "978" : "979"; - string group = _random.Next(0, 99999).ToString().PadLeft(5, '0'); - string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0'); - string title = _random.Next(0, 99).ToString().PadLeft(2, '0'); + string prefix = Random.Shared.Next(2) == 0 ? "978" : "979"; + string group = Random.Shared.Next(0, 99999).ToString().PadLeft(5, '0'); + string publisher = Random.Shared.Next(0, 999999).ToString().PadLeft(6, '0'); + string title = Random.Shared.Next(0, 99).ToString().PadLeft(2, '0'); string isbn = $"{prefix}{group[..1]}{publisher}{title}"; int sum = 0; diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs index 6aa7465e..073da4ba 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authentication/QRCodeGeneratorFixture.cs @@ -20,7 +20,7 @@ public class QRCodeGeneratorFixture { string username = new Faker().Person.UserName; byte[] secret = new byte[20]; // Standard TOTP secret length - new Random().NextBytes(secret); + Random.Shared.NextBytes(secret); return (username, secret); } diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs index 9347f4b9..a4002f41 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Themes/ThemePackFixture.cs @@ -28,8 +28,8 @@ public sealed class ThemePackFixture /// Optional template mappings written to the manifest. /// Optional preview path written to the manifest, or to omit the preview. /// Optional content for the default template file. - /// Whether to include the preview asset file in the archive or not. /// Optional additional files written into the archive. + /// Whether to include the preview asset file in the archive or not. /// The created theme pack ZIP archive. public byte[] Create( string themeId = "test-theme", @@ -41,8 +41,8 @@ public sealed class ThemePackFixture Dictionary? templates = null, string? preview = "assets/preview.png", string? defaultTemplateContent = null, - bool includePreviewAsset = true, - IReadOnlyDictionary? additionalFiles = null) + IReadOnlyDictionary? additionalFiles = null, + bool includePreviewAsset = true) { Dictionary manifestTemplates = templates ?? new Dictionary(StringComparer.OrdinalIgnoreCase) { diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs index ad6f31c8..601b9e36 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -272,12 +272,12 @@ public class StubApiHttpClient : IApiHttpClient /// /// The expected type of the response content. /// The API endpoint where the request is being sent. - /// The stream of the file to upload. - /// The name of the file to upload. + /// The stream of the file to upload, or when no file is uploaded. + /// The name of the file to upload, or when no file is uploaded. /// The name of the form field carrying the file. /// Cancellation token that can be used to stop the execution. /// The deserialized response containing the result of the PUT request. - public Task PutMultipartAsync(string endpoint, Stream fileStream, string fileName, string fieldName, CancellationToken cancellationToken = default) + public Task PutMultipartAsync(string endpoint, Stream? fileStream, string? fileName, string fieldName, CancellationToken cancellationToken = default) { PutRequests.Add((endpoint, fileName)); if (_putResponseFactories.TryGetValue(endpoint, out Func? responseFactory)) 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 1a3a0fdc..b3744d55 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 @@ -17,7 +17,6 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; public class ReleaseInfoDtoFixture { private readonly Faker _faker = new(); - private readonly Random _random = new(); /// /// Creates a new instance with randomized test data. @@ -37,9 +36,9 @@ public class ReleaseInfoDtoFixture ReleaseCountry? releaseCountry = null, string? releaseVersion = null) { - int resolvedOriginalReleaseYear = originalReleaseYear ?? (originalReleaseDate?.Year ?? _random.Next(1900, 2026)); + int resolvedOriginalReleaseYear = originalReleaseYear ?? (originalReleaseDate?.Year ?? Random.Shared.Next(1900, 2026)); DateOnly resolvedOriginalReleaseDate = originalReleaseDate ?? new DateOnly(resolvedOriginalReleaseYear, 1, 1); - int resolvedReReleaseYear = reReleaseYear ?? (reReleaseDate?.Year ?? _random.Next(resolvedOriginalReleaseYear, resolvedOriginalReleaseYear + 100)); + int resolvedReReleaseYear = reReleaseYear ?? (reReleaseDate?.Year ?? Random.Shared.Next(resolvedOriginalReleaseYear, resolvedOriginalReleaseYear + 100)); DateOnly resolvedReReleaseDate = reReleaseDate ?? new DateOnly(resolvedReReleaseYear, 1, 1); return new ReleaseInfoDto 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 f7b858a7..dc8aee52 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,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Presentation.Web.Common.DTO.MediaContributors; +using Lumina.Presentation.Web.Common.Enums.MediaContributors; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -14,7 +15,6 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaContributors; [ExcludeFromCodeCoverage] public class MediaContributorDtoFixture { - private static readonly string[] RoleCategories = ["Author", "Translator", "Illustrator", "Editor", "Narrator"]; private readonly Faker _faker = new(); /// @@ -22,16 +22,13 @@ public class MediaContributorDtoFixture /// /// Optional. The name by which the contributor is popularly known. /// Optional. The legal name of the contributor. - /// Optional. The name of the role of the contributor. - /// Optional. The category of the role of the contributor. + /// Optional. The canonical role of the contributor. /// A configured instance. public MediaContributorDto Create( string? displayName = null, string? legalName = null, - string? roleName = null, - string? roleCategory = null) + MediaContributorRole? role = null) { - string resolvedRoleCategory = roleCategory ?? _faker.Random.ArrayElement(RoleCategories); return new MediaContributorDto { Name = new MediaContributorNameDto @@ -39,11 +36,7 @@ public class MediaContributorDtoFixture DisplayName = displayName ?? _faker.Name.FullName(), LegalName = legalName ?? _faker.Name.FullName() }, - Role = new MediaContributorRoleDto - { - Name = roleName ?? resolvedRoleCategory.ToLowerInvariant(), - Category = resolvedRoleCategory - } + Role = role ?? MediaContributorRole.Author }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs index bf3edb3c..662a3cec 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs @@ -21,18 +21,18 @@ public class ThemeNavEntryDtoFixture /// /// Optional label of the entry. /// Optional URL of the link, or for a submenu. - /// Whether the URL should be included, or forced to . /// Optional CSS classes of the link. - /// Whether the CSS class should be included, or forced to . /// Optional child links of a submenu. + /// Whether the URL should be included, or forced to . + /// Whether the CSS class should be included, or forced to . /// The created . public ThemeNavEntryDto Create( string? label = null, string? url = null, - bool includeUrl = false, string? cssClass = null, - bool includeCssClass = false, - IReadOnlyList? children = null) + IReadOnlyList? children = null, + bool includeUrl = false, + bool includeCssClass = false) { return new ThemeNavEntryDto( Label: label ?? _faker.Lorem.Word(), 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 14ec2131..8cf8b0bb 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 @@ -28,12 +28,12 @@ public class ThemeResponseDtoFixture /// Optional author of the theme. /// Optional semantic version of the theme. /// Optional preview image path of the theme, or when the theme has no preview. - /// Whether the preview path should be included, or forced to . /// Optional source the theme was installed from. /// Optional value indicating whether the theme is the active one. - /// Whether the currently active flag should be included, or forced to . /// Optional UTC timestamp at which the theme was installed. /// Optional value indicating whether the theme was deleted by the user. + /// Whether the preview path should be included, or forced to . + /// Whether the currently active flag should be included, or forced to . /// A configured instance. public ThemeResponseDto Create( Guid? id = null, @@ -43,12 +43,12 @@ public class ThemeResponseDtoFixture string? author = null, string? version = null, string? previewPath = null, - bool includePreviewPath = false, ThemeInstallSource? installSource = null, bool? isCurrent = null, - bool includeIsCurrent = false, DateTime? installedAtUtc = null, - bool? isDeleted = null) + bool? isDeleted = null, + bool includePreviewPath = false, + bool includeIsCurrent = false) { return new ThemeResponseDto( Id: id ?? Guid.NewGuid(), 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 f5185f35..ead34981 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 @@ -15,7 +15,6 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.Book [ExcludeFromCodeCoverage] public class IsbnDtoFixture { - private readonly Random _random = new(); /// /// Creates a new instance with a random or explicitly requested format. @@ -51,7 +50,7 @@ public class IsbnDtoFixture { int[] digits = new int[9]; for (int i = 0; i < 9; i++) - digits[i] = _random.Next(0, 10); + digits[i] = Random.Shared.Next(0, 10); int sum = 0; for (int i = 0; i < 9; i++) @@ -69,10 +68,10 @@ public class IsbnDtoFixture /// A valid ISBN-13 value. private string GenerateValidIsbn13() { - string prefix = _random.Next(2) == 0 ? "978" : "979"; - string group = _random.Next(0, 99999).ToString().PadLeft(5, '0'); - string publisher = _random.Next(0, 999999).ToString().PadLeft(6, '0'); - string title = _random.Next(0, 99).ToString().PadLeft(2, '0'); + string prefix = Random.Shared.Next(2) == 0 ? "978" : "979"; + string group = Random.Shared.Next(0, 99999).ToString().PadLeft(5, '0'); + string publisher = Random.Shared.Next(0, 999999).ToString().PadLeft(6, '0'); + string title = Random.Shared.Next(0, 99).ToString().PadLeft(2, '0'); string isbn = $"{prefix}{group[..1]}{publisher}{title}"; int sum = 0; 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 new file mode 100644 index 00000000..8fa3f11c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The relative path of the stored cover image. + /// A configured instance. + public UpdateBookCoverDto Create(string? coverPath = null) + { + return new UpdateBookCoverDto + { + CoverPath = coverPath ?? _faker.System.FilePath() + }; + } + + /// + /// 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/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/FileSystemManagement/Directories/GetDirectoriesRequestFixture.cs index 6c3c7575..daf3c6d6 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 @@ -17,15 +17,15 @@ public class GetDirectoriesRequestFixture /// Creates a new instance with randomized test data. /// /// Optional file system path whose directories are retrieved. - /// Whether to include hidden file system elements or not. + /// Whether to include hidden file system elements or not. /// A configured instance. public GetDirectoriesRequest Create( string? path = null, - bool includeHiddenElements = false) + bool shouldIncludeHiddenElements = false) { return new GetDirectoriesRequest( Path: path ?? $"/media/{System.Guid.NewGuid():N}", - IncludeHiddenElements: includeHiddenElements + ShouldIncludeHiddenElements: shouldIncludeHiddenElements ); } 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 deca06c8..57f2062f 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 @@ -18,11 +18,13 @@ public class GetBookRequestFixture /// Creates a new instance. /// /// Optional unique identifier of the book to retrieve. + /// Optional unique identifier of the media library the book belongs to. /// A configured instance. public GetBookRequest Create( - Guid? id = null) + Guid? id = null, + Guid? libraryId = null) { - return new GetBookRequest(id?.ToString() ?? Guid.NewGuid().ToString()); + return new GetBookRequest(id?.ToString() ?? Guid.NewGuid().ToString(), libraryId ?? Guid.NewGuid()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequestFixture.cs index 77d65172..dceb8d74 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingAvailabilityRequestFixture.cs @@ -18,11 +18,13 @@ public class GetBookReadingAvailabilityRequestFixture /// Creates a random valid . /// /// Optional. The Id of the book whose reading availability is checked. + /// Optional. The Id of the media library the book belongs to. /// The created . public GetBookReadingAvailabilityRequest Create( - Guid? bookId = null) + Guid? bookId = null, + Guid? libraryId = null) { - return new GetBookReadingAvailabilityRequest(bookId ?? Guid.NewGuid()); + return new GetBookReadingAvailabilityRequest(bookId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequestFixture.cs index 7880433d..2e7d7dc6 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingManifestRequestFixture.cs @@ -18,11 +18,13 @@ public class GetBookReadingManifestRequestFixture /// Creates a random valid . /// /// Optional. The Id of the book whose reading manifest is retrieved. + /// Optional. The Id of the media library the book belongs to. /// The created . public GetBookReadingManifestRequest Create( - Guid? bookId = null) + Guid? bookId = null, + Guid? libraryId = null) { - return new GetBookReadingManifestRequest(bookId ?? Guid.NewGuid()); + return new GetBookReadingManifestRequest(bookId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequestFixture.cs index d79ef7aa..a1218094 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingResourceRequestFixture.cs @@ -19,12 +19,14 @@ public class GetBookReadingResourceRequestFixture /// /// Optional. The Id of the book whose resource is retrieved. /// Optional. The opaque resource key of the resource. + /// Optional. The Id of the media library the book belongs to. /// The created . public GetBookReadingResourceRequest Create( Guid? bookId = null, - string? resourceKey = null) + string? resourceKey = null, + Guid? libraryId = null) { - return new GetBookReadingResourceRequest(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}"); + return new GetBookReadingResourceRequest(bookId ?? Guid.NewGuid(), resourceKey ?? $"resource-{Guid.NewGuid():N}", libraryId ?? Guid.NewGuid()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequestFixture.cs index 1ff63095..30e254a0 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetBookReadingSectionRequestFixture.cs @@ -19,12 +19,14 @@ public class GetBookReadingSectionRequestFixture /// /// Optional. The Id of the book whose reading section is retrieved. /// Optional. The opaque location reference of the reading section. + /// Optional. The Id of the media library the book belongs to. /// The created . public GetBookReadingSectionRequest Create( Guid? bookId = null, - string? locationRef = null) + string? locationRef = null, + Guid? libraryId = null) { - return new GetBookReadingSectionRequest(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}"); + return new GetBookReadingSectionRequest(bookId ?? Guid.NewGuid(), locationRef ?? $"section-{Guid.NewGuid():N}", libraryId ?? Guid.NewGuid()); } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequestFixture.cs index 6c09f75e..0671ba1f 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/Reading/ReadBookViewRequestFixture.cs @@ -18,11 +18,13 @@ public class ReadBookViewRequestFixture /// Creates a random valid . /// /// Optional. The Id of the book to read. + /// Optional. The Id of the media library the book belongs to. /// The created . public ReadBookViewRequest Create( - Guid? bookId = null) + Guid? bookId = null, + Guid? libraryId = null) { - return new ReadBookViewRequest(bookId ?? Guid.NewGuid()); + return new ReadBookViewRequest(bookId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid()); } /// 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 675dc2f8..7e0dac00 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 @@ -31,34 +31,69 @@ public class UpdateBookRequestFixture /// Creates a new instance with randomized test data. /// /// Optional Id of the book to update. + /// Optional Id of the media library the book belongs to. /// Optional written content metadata of the book. - /// Whether the properties that are not explicitly provided should be randomized, or forced to . + /// Whether the metadata should be included, or forced to . + /// Whether the format should be included, or forced to . + /// Whether the edition should be included, or forced to . + /// Whether the volume number should be included, or forced to . + /// Whether the series should be included, or forced to . + /// Whether the ASIN should be included, or forced to . + /// Whether the Goodreads Id should be included, or forced to . + /// Whether the LCCN should be included, or forced to . + /// Whether the OCLC number should be included, or forced to . + /// Whether the Open Library Id should be included, or forced to . + /// Whether the LibraryThing Id should be included, or forced to . + /// Whether the Google Books Id should be included, or forced to . + /// Whether the Barnes and Noble Id should be included, or forced to . + /// Whether the Apple Books Id should be included, or forced to . + /// Whether the ISBNs should be included, or forced to . + /// Whether the contributors should be included, or forced to . + /// Whether the ratings should be included, or forced to . /// A configured instance. public UpdateBookRequest Create( Guid? id = null, + Guid? libraryId = null, WrittenContentMetadataDto? metadata = null, - bool includeOptionalProperties = true) + bool includeMetadata = true, + bool includeFormat = true, + bool includeEdition = true, + bool includeVolumeNumber = true, + bool includeSeries = true, + bool includeAsin = true, + bool includeGoodreadsId = true, + bool includeLccn = true, + bool includeOclcNumber = true, + bool includeOpenLibraryId = true, + bool includeLibraryThingId = true, + bool includeGoogleBooksId = true, + bool includeBarnesAndNobleId = true, + bool includeAppleBooksId = true, + bool includeIsbns = true, + bool includeContributors = true, + bool includeRatings = true) { return new UpdateBookRequest { - Id = id?.ToString() ?? Guid.NewGuid().ToString(), - Metadata = metadata ?? (includeOptionalProperties ? _writtenContentMetadataDtoFixture.Create() : null), - Format = includeOptionalProperties ? _faker.PickRandom() : null, - Edition = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, - VolumeNumber = includeOptionalProperties ? _faker.Random.Number(1, 3) : null, - Series = includeOptionalProperties ? _bookSeriesDtoFixture.Create() : null, - ASIN = includeOptionalProperties ? _faker.Random.String2(10) : null, - GoodreadsId = includeOptionalProperties ? _faker.Random.Number(100000, 500000).ToString() : null, - LCCN = includeOptionalProperties ? "n78890351" : null, - OCLCNumber = includeOptionalProperties ? "ocm12345678" : null, - OpenLibraryId = includeOptionalProperties ? "OL123456M" : null, - LibraryThingId = includeOptionalProperties ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, - GoogleBooksId = includeOptionalProperties ? CreateGoogleBooksId() : null, - BarnesAndNobleId = includeOptionalProperties ? _faker.Random.String2(10, "0123456789") : null, - AppleBooksId = includeOptionalProperties ? $"id{_faker.Random.Number(1, 999999)}" : null, - ISBNs = includeOptionalProperties ? [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null, - Contributors = includeOptionalProperties ? [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null, - Ratings = includeOptionalProperties ? [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null + BookId = id?.ToString() ?? Guid.NewGuid().ToString(), + LibraryId = libraryId ?? Guid.NewGuid(), + Metadata = includeMetadata ? (metadata ?? _writtenContentMetadataDtoFixture.Create()) : null, + Format = includeFormat ? _faker.PickRandom() : null, + Edition = includeEdition ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + VolumeNumber = includeVolumeNumber ? _faker.Random.Number(1, 3) : null, + Series = includeSeries ? _bookSeriesDtoFixture.Create() : null, + ASIN = includeAsin ? _faker.Random.String2(10) : null, + GoodreadsId = includeGoodreadsId ? _faker.Random.Number(100000, 500000).ToString() : null, + LCCN = includeLccn ? "n78890351" : null, + OCLCNumber = includeOclcNumber ? "ocm12345678" : null, + OpenLibraryId = includeOpenLibraryId ? "OL123456M" : null, + LibraryThingId = includeLibraryThingId ? _faker.Random.String2(_faker.Random.Number(1, 50)) : null, + GoogleBooksId = includeGoogleBooksId ? CreateGoogleBooksId() : null, + BarnesAndNobleId = includeBarnesAndNobleId ? _faker.Random.String2(10, "0123456789") : null, + AppleBooksId = includeAppleBooksId ? $"id{_faker.Random.Number(1, 999999)}" : null, + ISBNs = includeIsbns ? [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null, + Contributors = includeContributors ? [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null, + Ratings = includeRatings ? [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null }; } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Authorization/RoleRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Authorization/RoleRepositoryTests.cs new file mode 100644 index 00000000..7efca6af --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Authorization/RoleRepositoryTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.DataAccess.Core.Repositories.Authorization; +using Lumina.DataAccess.Core.UoW; +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.Authorization; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class RoleRepositoryTests +{ + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-rolerepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + RoleRepository sut = new(context); + + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + RoleEntity storedRole = _roleEntityFixture.Create(roleName: "Admin", createdOnUtc: storedCreatedOnUtc, createdBy: storedCreatedBy); + context.Roles.Add(storedRole); + await context.SaveChangesAsync(); + + RoleEntity updatedRole = _roleEntityFixture.Create(id: storedRole.Id, roleName: "SuperAdmin", createdOnUtc: DateTime.UtcNow.AddYears(-10), createdBy: Guid.NewGuid()); + updatedRole.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5); + updatedRole.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(updatedRole, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + RoleEntity reloadedRole = await context.Roles.AsNoTracking().FirstAsync(role => role.Id == storedRole.Id); + Assert.Equal("SuperAdmin", reloadedRole.RoleName); + Assert.Equal(storedCreatedOnUtc, reloadedRole.CreatedOnUtc); + Assert.Equal(storedCreatedBy, reloadedRole.CreatedBy); + Assert.Null(reloadedRole.UpdatedOnUtc); + Assert.Null(reloadedRole.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateThePermissions() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-rolerepo-permissions-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + RoleRepository sut = new(context); + + PermissionEntity firstPermission = _permissionEntityFixture.Create(); + PermissionEntity secondPermission = _permissionEntityFixture.Create(); + RoleEntity storedRole = _roleEntityFixture.Create(roleName: $"perm-role-{Guid.NewGuid():N}"); + context.Permissions.AddRange(firstPermission, secondPermission); + context.Roles.Add(storedRole); + await context.SaveChangesAsync(); + storedRole.RolePermissions.Add(_rolePermissionEntityFixture.Create(role: storedRole, permission: firstPermission)); + storedRole.RolePermissions.Add(_rolePermissionEntityFixture.Create(role: storedRole, permission: secondPermission)); + await context.SaveChangesAsync(); + // Detach the seeded role, so that the update must load it through its include chain instead of returning the already populated seeded instance. + context.ChangeTracker.Clear(); + + RoleEntity incoming = await context.Roles.AsNoTracking().Include(candidate => candidate.RolePermissions).FirstAsync(candidate => candidate.Id == storedRole.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + RoleEntity? reloadedRole = await context.Roles.AsNoTracking().Include(candidate => candidate.RolePermissions).FirstOrDefaultAsync(candidate => candidate.Id == storedRole.Id); + Assert.NotNull(reloadedRole); + Assert.Equal(2, reloadedRole!.RolePermissions.Count); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs new file mode 100644 index 00000000..2c235bef --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -0,0 +1,483 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.Repositories.BookLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +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.DataAccess.IntegrationTests.Core.Repositories.BookLibrary; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class BookRepositoryTests +{ + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); + private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); + private readonly IsbnEntityFixture _isbnEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + + [Fact] + public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths() + { + // Arrange + // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity changedBook = _bookEntityFixture.Create(); + changedBook.LibraryId = libraryId; + changedBook.Path = "/books/changed.epub"; + changedBook.MetadataStatus = MetadataStatus.Enriched; + changedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity unchangedBook = _bookEntityFixture.Create(); + unchangedBook.LibraryId = libraryId; + unchangedBook.Path = "/books/unchanged.epub"; + unchangedBook.MetadataStatus = MetadataStatus.Enriched; + unchangedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + context.Books.AddRange(changedBook, unchangedBook); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.Artwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id); + Assert.NotNull(resetBook); + Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); + Assert.Equal(ArtworkStatus.Pending, resetBook.Artwork.Single().Status); + BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id); + Assert.NotNull(keptBook); + Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); + } + + [Fact] + public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary() + { + // Arrange + // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity enrichedBook = _bookEntityFixture.Create(); + enrichedBook.LibraryId = libraryId; + enrichedBook.MetadataStatus = MetadataStatus.Enriched; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched; + context.Books.AddRange(enrichedBook, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id); + Assert.NotNull(resetBook); + Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); + BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id); + Assert.NotNull(keptBook); + Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); + } + + [Fact] + public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks() + { + // Arrange + // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); + bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); + bookOfAnotherLibrary.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + context.Books.AddRange(book, bookOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + BookArtworkEntity? resetArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id); + Assert.NotNull(resetArtwork); + Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status); + BookArtworkEntity? keptArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id); + Assert.NotNull(keptArtwork); + Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status); + } + + [Fact] + public async Task InsertAsync_WhenCalledWithAValidBook_ShouldPersistTheBook() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + BookEntity book = _bookEntityFixture.Create(); + + // Act + Result result = await sut.InsertAsync(book, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + BookEntity? storedBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Equal(book.Path, storedBook!.Path); + Assert.Equal(book.Title, storedBook.Title); + } + + [Fact] + public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnBookAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + BookEntity existingBook = _bookEntityFixture.Create(); + existingBook.LibraryId = libraryId; + existingBook.Path = "/books/existing.epub"; + context.Books.Add(existingBook); + await context.SaveChangesAsync(); + + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.Path = "/books/existing.epub"; + + // Act + Result result = await sut.InsertAsync(book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; + book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; + book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid contributorId = book.Contributors[0].Id; + DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Null(storedBook!.UpdatedOnUtc); + BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenOnlyTheMetadataChanged_ShouldStampTheBookAndKeepTheChildRowsUntouched() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-metadata-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + book.Contributors = [_bookContributorEntityFixture.Create(bookId: book.Id)]; + book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks)]; + book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13)]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid contributorId = book.Contributors[0].Id; + DateTime contributorCreatedOnUtc = book.Contributors[0].CreatedOnUtc; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + incoming.Title = "A brand new title"; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? storedBook = await context.Books.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Equal("A brand new title", storedBook!.Title); + Assert.Equal(utcNow, storedBook.UpdatedOnUtc); + Assert.Equal(userId, storedBook.UpdatedBy); + BookContributorEntity storedContributor = Assert.Single(storedBook.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + Guid keptMediaContributorId = Guid.NewGuid(); + BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); + BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()); + book.Contributors = [keptContributor, removedContributor]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync(); + BookContributorEntity storedContributor = Assert.Single(storedContributors); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsAdded_ShouldInsertOnlyTheNewParticipationAndKeepTheExistingIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-addcontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + BookRepository sut = new(context); + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + Guid keptMediaContributorId = Guid.NewGuid(); + BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: keptMediaContributorId); + book.Contributors = [keptContributor]; + context.Books.Add(book); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + Guid addedMediaContributorId = Guid.NewGuid(); + incoming.Contributors.Add(_bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: addedMediaContributorId)); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set().AsNoTracking().Where(contributor => contributor.BookId == book.Id).ToListAsync(); + Assert.Equal(2, storedContributors.Count); + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateAnyReconciledChildCollection() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-noop-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + book.Tags = [_tagEntityFixture.Create(name: $"noop-book-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-book-tag-two-{Guid.NewGuid():N}")]; + book.Genres = [_genreEntityFixture.Create(name: $"noop-book-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-book-genre-two-{Guid.NewGuid():N}")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13), _isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)]; + book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks), _bookRatingEntityFixture.Create(source: BookRatingSource.Goodreads)]; + book.Contributors = + [ + _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()), + _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()) + ]; + context.Books.Add(book); + await context.SaveChangesAsync(); + // Detach the seeded graph, so that the update must load the tracked book through its include chain instead of returning the already populated seeded instance. + context.ChangeTracker.Clear(); + + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? storedBook = await context.Books + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.ISBNs) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Equal(2, storedBook!.Tags.Count); + Assert.Equal(2, storedBook.Genres.Count); + Assert.Equal(2, storedBook.ISBNs.Count); + Assert.Equal(2, storedBook.Ratings.Count); + Assert.Equal(2, storedBook.Contributors.Count); + } + + [Fact] + public async Task UpdateAsync_WhenOneItemIsRemovedFromEachReconciledChildCollection_ShouldRemoveOnlyThoseItems() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-update-remove-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + BookRepository sut = new(context); + + string keptTagName = $"remove-book-tag-{Guid.NewGuid():N}"; + string keptGenreName = $"remove-book-genre-{Guid.NewGuid():N}"; + BookEntity book = _bookEntityFixture.Create(includeMetadata: false); + book.Tags = [_tagEntityFixture.Create(name: keptTagName), _tagEntityFixture.Create(name: $"remove-book-tag-two-{Guid.NewGuid():N}")]; + book.Genres = [_genreEntityFixture.Create(name: keptGenreName), _genreEntityFixture.Create(name: $"remove-book-genre-two-{Guid.NewGuid():N}")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "9783161484100", format: IsbnFormat.Isbn13), _isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)]; + book.Ratings = [_bookRatingEntityFixture.Create(source: BookRatingSource.GoogleBooks), _bookRatingEntityFixture.Create(source: BookRatingSource.Goodreads)]; + BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid()); + book.Contributors = [keptContributor, _bookContributorEntityFixture.Create(bookId: book.Id, mediaContributorId: Guid.NewGuid())]; + context.Books.Add(book); + await context.SaveChangesAsync(); + // Detach the seeded graph, so that the update must load the tracked book through its include chain instead of returning the already populated seeded instance. + context.ChangeTracker.Clear(); + + BookEntity incoming = await LoadDetachedBookAsync(context, book.Id); + incoming.Tags = [incoming.Tags.Single(tag => tag.Name == keptTagName)]; + incoming.Genres = [incoming.Genres.Single(genre => genre.Name == keptGenreName)]; + incoming.ISBNs = [incoming.ISBNs.Single(isbn => isbn.Value == "9783161484100")]; + incoming.Ratings = [incoming.Ratings.Single(rating => rating.Source == BookRatingSource.GoogleBooks)]; + incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.Id == keptContributor.Id)]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? storedBook = await context.Books + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.ISBNs) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == book.Id); + Assert.NotNull(storedBook); + Assert.Equal(keptTagName, Assert.Single(storedBook!.Tags).Name); + Assert.Equal(keptGenreName, Assert.Single(storedBook.Genres).Name); + Assert.Equal("9783161484100", Assert.Single(storedBook.ISBNs).Value); + Assert.Equal(BookRatingSource.GoogleBooks, Assert.Single(storedBook.Ratings).Source); + Assert.Equal(keptContributor.Id, Assert.Single(storedBook.Contributors).Id); + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Loads a detached copy of a stored book, with its children, so that it can be handed to the repository as the desired state of an edit. + /// + /// The context that tracks the stored book. + /// The Id of the book to load. + /// The detached copy of the book. + private static async Task LoadDetachedBookAsync(LuminaDbContext context, Guid bookId) + { + return await context.Books + .AsNoTracking() + .Include(book => book.Tags) + .Include(book => book.Genres) + .Include(book => book.ISBNs) + .Include(book => book.Ratings) + .Include(book => book.Contributors) + .FirstAsync(book => book.Id == bookId); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs deleted file mode 100644 index 0d408200..00000000 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs +++ /dev/null @@ -1,138 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.DataAccess.Core.Repositories.Books; -using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Microsoft.Data.Sqlite; -using Microsoft.EntityFrameworkCore; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Books; - -/// -/// Contains integration tests for the class, exercising it against a real SQLite database. -/// -[ExcludeFromCodeCoverage] -public class BookRepositoryTests -{ - private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); - - [Fact] - public async Task ResetEnrichmentStateForPathsAsync_WhenCalled_ShouldResetTheMetadataAndArtworkStatusesForThePaths() - { - // Arrange - // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. - using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); - anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); - context.Database.EnsureCreated(); - BookRepository sut = new(context); - - Guid libraryId = Guid.NewGuid(); - BookEntity changedBook = _bookEntityFixture.Create(); - changedBook.LibraryId = libraryId; - changedBook.Path = "/books/changed.epub"; - changedBook.MetadataStatus = MetadataStatus.Enriched; - changedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: changedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - BookEntity unchangedBook = _bookEntityFixture.Create(); - unchangedBook.LibraryId = libraryId; - unchangedBook.Path = "/books/unchanged.epub"; - unchangedBook.MetadataStatus = MetadataStatus.Enriched; - unchangedBook.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - context.Books.AddRange(changedBook, unchangedBook); - await context.SaveChangesAsync(); - - // Act - Result result = await sut.ResetEnrichmentStateForPathsAsync(libraryId, ["/books/changed.epub"], CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Updated, result.Value); - BookEntity? resetBook = await context.Books.AsNoTracking().Include(book => book.BookArtwork).FirstOrDefaultAsync(book => book.Id == changedBook.Id); - Assert.NotNull(resetBook); - Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); - Assert.Equal(ArtworkStatus.Pending, resetBook.BookArtwork.Single().Status); - BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == unchangedBook.Id); - Assert.NotNull(keptBook); - Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); - } - - [Fact] - public async Task ResetMetadataStatusForLibraryAsync_WhenCalled_ShouldResetTheMetadataStatusOfAllBooksOfTheLibrary() - { - // Arrange - // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. - using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); - anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); - context.Database.EnsureCreated(); - BookRepository sut = new(context); - - Guid libraryId = Guid.NewGuid(); - BookEntity enrichedBook = _bookEntityFixture.Create(); - enrichedBook.LibraryId = libraryId; - enrichedBook.MetadataStatus = MetadataStatus.Enriched; - BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); - bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); - bookOfAnotherLibrary.MetadataStatus = MetadataStatus.Enriched; - context.Books.AddRange(enrichedBook, bookOfAnotherLibrary); - await context.SaveChangesAsync(); - - // Act - Result result = await sut.ResetMetadataStatusForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Updated, result.Value); - BookEntity? resetBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == enrichedBook.Id); - Assert.NotNull(resetBook); - Assert.Equal(MetadataStatus.Pending, resetBook!.MetadataStatus); - BookEntity? keptBook = await context.Books.AsNoTracking().FirstOrDefaultAsync(book => book.Id == bookOfAnotherLibrary.Id); - Assert.NotNull(keptBook); - Assert.Equal(MetadataStatus.Enriched, keptBook!.MetadataStatus); - } - - [Fact] - public async Task ResetArtworkStatusForLibraryAsync_WhenCalled_ShouldResetTheArtworkStatusOfTheLibraryBooks() - { - // Arrange - // The reset methods use ExecuteUpdateAsync, which is not supported by the in-memory provider, so a real SQLite database is used. - using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-bookrepo-reset-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); - anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); - context.Database.EnsureCreated(); - BookRepository sut = new(context); - - Guid libraryId = Guid.NewGuid(); - BookEntity book = _bookEntityFixture.Create(); - book.LibraryId = libraryId; - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); - bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); - bookOfAnotherLibrary.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; - context.Books.AddRange(book, bookOfAnotherLibrary); - await context.SaveChangesAsync(); - - // Act - Result result = await sut.ResetArtworkStatusForLibraryAsync(libraryId, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(Result.Updated, result.Value); - BookArtworkEntity? resetArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == book.Id); - Assert.NotNull(resetArtwork); - Assert.Equal(ArtworkStatus.Pending, resetArtwork!.Status); - BookArtworkEntity? keptArtwork = await context.Set().AsNoTracking().FirstOrDefaultAsync(artwork => artwork.BookId == bookOfAnotherLibrary.Id); - Assert.NotNull(keptArtwork); - Assert.Equal(ArtworkStatus.Enriched, keptArtwork!.Status); - } -} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs new file mode 100644 index 00000000..38a71a90 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +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.DataAccess.IntegrationTests.Core.Repositories.Libraries; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class LibraryRepositoryTests +{ + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeTheLibraryAudit() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + LibraryRepository sut = new(context); + context.Users.Add(_userEntityFixture.Create(id: userId)); + LibraryEntity library = _libraryEntityFixture.Create(userId: userId, contentLocations: ["/media/one", "/media/two"]); + context.Libraries.Add(library); + await context.SaveChangesAsync(); + LibraryEntity incoming = await LoadDetachedLibraryAsync(context, library.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().Include(candidate => candidate.ContentLocations).FirstOrDefaultAsync(candidate => candidate.Id == library.Id); + Assert.NotNull(storedLibrary); + Assert.Null(storedLibrary!.UpdatedOnUtc); + Assert.Equal(2, storedLibrary.ContentLocations.Count); + } + + [Fact] + public async Task UpdateAsync_WhenContentLocationsChange_ShouldApplyOnlyTheDeltasAndKeepTheUnchangedOnes() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-locations-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + LibraryRepository sut = new(context); + context.Users.Add(_userEntityFixture.Create(id: userId)); + LibraryEntity library = _libraryEntityFixture.Create(userId: userId, contentLocations: ["/media/one", "/media/two", "/media/keep"]); + context.Libraries.Add(library); + await context.SaveChangesAsync(); + Guid keptLocationId = context.Entry(library.ContentLocations.Single(location => location.Path == "/media/keep")).Property("Id").CurrentValue; + Guid retainedLocationId = context.Entry(library.ContentLocations.Single(location => location.Path == "/media/one")).Property("Id").CurrentValue; + 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 }); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().Include(candidate => candidate.ContentLocations).FirstOrDefaultAsync(candidate => candidate.Id == library.Id); + Assert.NotNull(storedLibrary); + Assert.Equal(3, storedLibrary!.ContentLocations.Count); + Assert.Equal(["/media/keep", "/media/one", "/media/three"], [.. storedLibrary.ContentLocations.Select(location => location.Path).OrderBy(path => path)]); + // The two locations that did not change must keep their stored row identity, instead of being deleted and re-inserted. + Assert.Equal(retainedLocationId, context.Entry(library.ContentLocations.Single(location => location.Path == "/media/one")).Property("Id").CurrentValue); + Assert.Equal(keptLocationId, context.Entry(library.ContentLocations.Single(location => location.Path == "/media/keep")).Property("Id").CurrentValue); + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Loads a detached copy of a stored library, with its content locations, so that it can be handed to the repository as the desired state of an edit. + /// + /// The context that tracks the stored library. + /// The Id of the library to load. + /// The detached copy of the library. + private static async Task LoadDetachedLibraryAsync(LuminaDbContext context, Guid libraryId) + { + return await context.Libraries + .AsNoTracking() + .Include(library => library.ContentLocations) + .FirstAsync(library => library.Id == libraryId); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs new file mode 100644 index 00000000..8769e260 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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.Libraries; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanRepositoryTests +{ + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns() + { + // 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(); + + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + LibraryScanEntity storedScan = _libraryScanEntityFixture.Create(libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Running, libraryEntity: storedLibrary); + storedScan.CreatedOnUtc = storedCreatedOnUtc; + storedScan.CreatedBy = storedCreatedBy; + context.LibraryScans.Add(storedScan); + await context.SaveChangesAsync(); + + LibraryScanEntity updatedScan = _libraryScanEntityFixture.Create(id: storedScan.Id, libraryId: storedLibrary.Id, userId: storedUser.Id, status: LibraryScanJobStatus.Completed, libraryEntity: storedLibrary); + updatedScan.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + updatedScan.CreatedBy = Guid.NewGuid(); + updatedScan.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5); + updatedScan.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(updatedScan, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + LibraryScanEntity reloadedScan = await context.LibraryScans.AsNoTracking().FirstAsync(scan => scan.Id == storedScan.Id); + Assert.Equal(LibraryScanJobStatus.Completed, reloadedScan.Status); + Assert.Equal(storedCreatedOnUtc, reloadedScan.CreatedOnUtc); + Assert.Equal(storedCreatedBy, reloadedScan.CreatedBy); + Assert.Null(reloadedScan.UpdatedOnUtc); + Assert.Null(reloadedScan.UpdatedBy); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs new file mode 100644 index 00000000..a6cdd694 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs @@ -0,0 +1,735 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +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.MediaContributors; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +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.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class AlbumRepositoryTests +{ + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + [Fact] + public async Task InsertAsync_WhenCalledWithAValidAlbum_ShouldPersistTheAlbumAndItsAggregate() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = BuildFullAlbum(artist.Id, libraryId, "A Night at the Opera"); + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + AlbumEntity? storedAlbum = await context.Albums + .AsNoTracking() + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.Contributors) + .Include(candidate => candidate.Tracks) + .ThenInclude(candidate => candidate.Moods) + .AsSplitQuery() + .FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Equal("A Night at the Opera", storedAlbum!.Title); + Assert.Single(storedAlbum.Ratings); + Assert.Equal(2, storedAlbum.Tags.Count); + Assert.Equal(2, storedAlbum.Genres.Count); + Assert.Single(storedAlbum.Contributors); + TrackEntity storedTrack = Assert.Single(storedAlbum.Tracks); + Assert.Equal(2, storedTrack.Moods.Count); + // Each tag and genre of the aggregate is stored exactly once. + Assert.Single(await context.Set().Where(tag => tag.Name == "album-tag-1").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "album-genre-1").ToListAsync()); + } + + [Fact] + public async Task InsertAsync_WhenAlbumWithTheSameIdAlreadyExists_ShouldReturnAlbumAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-id-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity existingAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + context.Albums.Add(existingAlbum); + await context.SaveChangesAsync(); + + AlbumEntity album = _albumEntityFixture.Create(id: existingAlbum.Id, artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-duprequest-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + album.Tracks = + [ + _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false), + _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false) + ]; + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-storedpath-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity existingAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Existing"); + context.Tracks.Add(_trackEntityFixture.Create( + albumId: existingAlbum.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)); + await context.SaveChangesAsync(); + + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheAlbum() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid firstLibraryId = Guid.NewGuid(); + ArtistEntity firstArtist = await SeedArtistAsync(context, firstLibraryId); + AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId, firstArtist.Id, "First"); + context.Tracks.Add(_trackEntityFixture.Create( + albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)); + await context.SaveChangesAsync(); + + Guid secondLibraryId = Guid.NewGuid(); + ArtistEntity secondArtist = await SeedArtistAsync(context, secondLibraryId); + AlbumEntity album = _albumEntityFixture.Create(artistId: secondArtist.Id, libraryId: secondLibraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: secondLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)]; + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Equal(secondLibraryId, storedAlbum!.LibraryId); + } + + [Fact] + public async Task InsertAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-reuse-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + context.Set().Add(_tagEntityFixture.Create(name: "ExistingTag")); + context.Set().Add(_genreEntityFixture.Create(name: "ExistingGenre")); + await context.SaveChangesAsync(); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + album.Tracks = [track]; + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + // The shared rows are reused instead of being duplicated. + Assert.Single(await context.Set().Where(tag => tag.Name == "ExistingTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "ExistingGenre").ToListAsync()); + } + + [Fact] + public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldPersistItOnce() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-insert-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + album.Tracks = [track]; + + // Act + Result result = await sut.InsertAsync(album, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The name shared by the album and its tracks is persisted exactly once. + Assert.Single(await context.Set().Where(tag => tag.Name == "SharedNewTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "SharedNewGenre").ToListAsync()); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera"); + Guid contributorId = album.Contributors[0].Id; + DateTime contributorCreatedOnUtc = album.Contributors[0].CreatedOnUtc; + // Detach the seeded graph, so that the update must load the tracked album through its include chain instead of returning the already populated seeded instance. + context.ChangeTracker.Clear(); + AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Null(storedAlbum!.UpdatedOnUtc); + AlbumContributorEntity storedContributor = Assert.Single(storedAlbum.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + Assert.Single(await context.Set().Where(tag => tag.Name == "album-tag-1").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "album-genre-1").ToListAsync()); + } + + [Fact] + public async Task UpdateAsync_WhenOnlyTheScalarValuesChanged_ShouldStampTheAlbumAndPreserveArtistAndLibrary() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-scalars-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera"); + AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id); + incoming.Title = "A Night at the Opera (Remastered)"; + incoming.ArtistId = Guid.NewGuid(); + incoming.LibraryId = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Equal("A Night at the Opera (Remastered)", storedAlbum!.Title); + // The stored identity is preserved and only the actual edit is stamped. + Assert.Equal(artist.Id, storedAlbum.ArtistId); + Assert.Equal(libraryId, storedAlbum.LibraryId); + Assert.Equal(utcNow, storedAlbum.UpdatedOnUtc); + Assert.Equal(userId, storedAlbum.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenRatingsAndContributorsChange_ShouldReconcileThem() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-update-owned-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + Guid keptMediaContributorId = Guid.NewGuid(); + Guid removedMediaContributorId = Guid.NewGuid(); + Guid addedMediaContributorId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20) + ]; + album.Contributors = + [ + _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer), + _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer) + ]; + context.Albums.Add(album); + await context.SaveChangesAsync(); + + AlbumEntity incoming = await LoadDetachedAlbumAsync(context, album.Id); + incoming.Ratings = + [ + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5) + ]; + incoming.Contributors = + [ + _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer), + _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals) + ]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? storedAlbum = await context.Albums + .AsNoTracking() + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Equal(3, storedAlbum!.Ratings.Count); + Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M); + Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M); + Assert.Contains(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M); + Assert.DoesNotContain(storedAlbum.Ratings, rating => rating.Source == AudioRatingSource.LastFm); + Assert.Equal(2, storedAlbum.Contributors.Count); + Assert.DoesNotContain(storedAlbum.Contributors, contributor => contributor.MediaContributorId == removedMediaContributorId); + Assert.Contains(storedAlbum.Contributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task GetByIdAsync_WhenAlbumExists_ShouldIncludeTheNavigationProperties() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = await SeedFullAlbumAsync(context, libraryId, artist.Id, "A Night at the Opera"); + + // Act + Result result = await sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity retrievedAlbum = result.Value!; + Assert.NotNull(retrievedAlbum.Artist); + Assert.Equal(artist.Id, retrievedAlbum.Artist!.Id); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Single(retrievedTrack.Ratings); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Equal(2, retrievedTrack.Isrcs.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedAlbum() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + context.Albums.Add(album); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + // Act + Result result = await sut.GetByIdAsync( + album.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Empty(context.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldNotTrackTheEntities() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + context.Albums.Add(album); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + // Act + Result> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value.Data); + Assert.Empty(context.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetByArtistIdAsync_WhenCalled_ShouldReturnTheArtistAlbumsOrderedWithTheirCollections() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-getbyartist-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity betaAlbum = await SeedFullAlbumAsync(context, libraryId, artist.Id, "Beta"); + AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha"); + ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId); + AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create( + artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false); + context.Albums.Add(albumOfAnotherArtist); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetByArtistIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Select(album => album.Id)); + AlbumEntity retrievedAlbum = result.Value.Single(album => album.Id == betaAlbum.Id); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistAlbumsOrdered() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-null-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + AlbumEntity betaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Beta"); + AlbumEntity alphaAlbum = await SeedAlbumAsync(context, libraryId, artist.Id, "Alpha"); + ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId); + AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create( + artistId: otherArtist.Id, libraryId: libraryId, title: "Gamma", includeTracks: false, includeMetadata: false); + context.Albums.Add(albumOfAnotherArtist); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([alphaAlbum.Id, betaAlbum.Id], result.Value.Data.Select(row => row.Id)); + Assert.Equal(2, result.Value.Count); + Assert.Equal(1, result.Value.CurrentPage); + Assert.Equal(2, result.Value.PerPage); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-albumrepo-lite-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + AlbumRepository sut = CreateAlbumRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId); + List albums = _albumEntityFixture.CreateMany(5); + for (int index = 0; index < albums.Count; index++) + { + albums[index].ArtistId = artist.Id; + albums[index].LibraryId = libraryId; + albums[index].Title = $"Album {index}"; + albums[index].Tracks = []; + } + context.Albums.AddRange(albums); + await context.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + + // Act + Result> result = await sut.GetAlbumsLiteByArtistIdAsync(artist.Id, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(5, result.Value.Count); + Assert.Equal(3, result.Value.NumberOfPages); + Assert.Equal(expectedCurrentPage, result.Value.CurrentPage); + Assert.Equal(perPage, result.Value.PerPage); + Assert.Equal(expectedRowCount, result.Value.Data.Count); + } + + /// + /// Creates an album repository backed by the provided context, wiring the real track repository. + /// + /// The context the repository operates on. + /// The created repository. + private static AlbumRepository CreateAlbumRepository(LuminaDbContext context) + { + return new AlbumRepository(context, new TrackRepository(context)); + } + + /// + /// Seeds an artist with no albums or contributors, so that the required foreign key of an album is satisfied. + /// + /// The context the artist is persisted through. + /// The Id of the library that owns the artist. + /// The persisted artist. + private async Task SeedArtistAsync(LuminaDbContext context, Guid libraryId) + { + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + context.Artists.Add(artist); + await context.SaveChangesAsync(); + return artist; + } + + /// + /// Seeds an album that belongs to the artist identified by . + /// + /// The context the album is persisted through. + /// The Id of the library that owns the album. + /// The Id of the artist that owns the album. + /// The title of the album. + /// The persisted album. + private async Task SeedAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title) + { + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false); + context.Albums.Add(album); + await context.SaveChangesAsync(); + return album; + } + + /// + /// Seeds an album with one track, including every related collection deterministically. + /// + /// The context the album is persisted through. + /// The Id of the library that owns the album. + /// The Id of the artist that owns the album. + /// The title of the album. + /// The persisted album. + private async Task SeedFullAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title) + { + AlbumEntity album = BuildFullAlbum(artistId, libraryId, title); + context.Albums.Add(album); + await context.SaveChangesAsync(); + return album; + } + + /// + /// Builds an album with one track, including every related collection deterministically, without persisting it. + /// + /// The Id of the artist that owns the album. + /// The Id of the library that owns the album. + /// The title of the album. + /// The created album. + private AlbumEntity BuildFullAlbum(Guid artistId, Guid libraryId, string title) + { + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false); + album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + album.Tags = [_tagEntityFixture.Create(name: "album-tag-1"), _tagEntityFixture.Create(name: "album-tag-2")]; + album.Genres = [_genreEntityFixture.Create(name: "album-genre-1"), _genreEntityFixture.Create(name: "album-genre-2")]; + album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)]; + track.Tags = [_tagEntityFixture.Create(name: "track-tag-1"), _tagEntityFixture.Create(name: "track-tag-2")]; + track.Genres = [_genreEntityFixture.Create(name: "track-genre-1"), _genreEntityFixture.Create(name: "track-genre-2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + album.Tracks = [track]; + return album; + } + + /// + /// Loads a detached copy of a stored album with the whole aggregate, so that it can be handed to the repository as the desired state of an edit. + /// + /// The context that tracks the stored album. + /// The Id of the album to load. + /// The detached copy of the album. + private static async Task LoadDetachedAlbumAsync(LuminaDbContext context, Guid albumId) + { + return await context.Albums + .AsNoTracking() + .Include(album => album.Ratings) + .Include(album => album.Tags) + .Include(album => album.Genres) + .Include(album => album.Contributors) + .Include(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .Include(album => album.Tracks) + .ThenInclude(track => track.Genres) + .Include(album => album.Tracks) + .ThenInclude(track => track.Tags) + .Include(album => album.Tracks) + .ThenInclude(track => track.Moods) + .Include(album => album.Tracks) + .ThenInclude(track => track.Isrcs) + .Include(album => album.Tracks) + .ThenInclude(track => track.Contributors) + .AsSplitQuery() + .FirstAsync(album => album.Id == albumId); + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs new file mode 100644 index 00000000..3aae0a38 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs @@ -0,0 +1,1305 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Filtering; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +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.MediaContributors; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class ArtistRepositoryTests +{ + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly ArtistContributorEntityFixture _artistContributorEntityFixture = new(); + private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new(); + + [Fact] + public async Task InsertAsync_WhenCalledWithAValidArtist_ShouldPersistTheArtistAndItsAggregate() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Contributors = + [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "InsertAlbumTag")]; + album.Genres = [_genreEntityFixture.Create(name: "InsertAlbumGenre")]; + album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "InsertTrackTag")]; + track.Genres = [_genreEntityFixture.Create(name: "InsertTrackGenre")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + album.Tracks = [track]; + artist.Albums = [album]; + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + ArtistEntity? storedArtist = await context.Artists + .AsNoTracking() + .Include(candidate => candidate.Contributors) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Ratings) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Tags) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Genres) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Contributors) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Tracks) + .ThenInclude(candidate => candidate.Tags) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Tracks) + .ThenInclude(candidate => candidate.Genres) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Tracks) + .ThenInclude(candidate => candidate.Moods) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Tracks) + .ThenInclude(candidate => candidate.Isrcs) + .AsSplitQuery() + .FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + Assert.Single(storedArtist!.Contributors); + AlbumEntity storedAlbum = Assert.Single(storedArtist.Albums); + Assert.Single(storedAlbum.Ratings); + Assert.Single(storedAlbum.Tags); + Assert.Single(storedAlbum.Genres); + Assert.Single(storedAlbum.Contributors); + TrackEntity storedTrack = Assert.Single(storedAlbum.Tracks); + Assert.Equal("/music/queen/bohemian-rhapsody.flac", storedTrack.Path); + Assert.Single(storedTrack.Tags); + Assert.Single(storedTrack.Genres); + Assert.Single(storedTrack.Moods); + Assert.Single(storedTrack.Isrcs); + // Each tag and genre referenced by the aggregate is stored exactly once. + Assert.Single(await context.Set().Where(tag => tag.Name == "InsertAlbumTag").ToListAsync()); + Assert.Single(await context.Set().Where(tag => tag.Name == "InsertTrackTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "InsertAlbumGenre").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "InsertTrackGenre").ToListAsync()); + } + + [Fact] + public async Task InsertAsync_WhenArtistWithTheSameIdAlreadyExists_ShouldReturnArtistAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-id-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + ArtistEntity existingArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + context.Artists.Add(existingArtist); + await context.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(id: existingArtist.Id, includeAlbums: false, includeContributors: false); + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherArtistOfTheSameLibraryHasTheSameName_ShouldReturnArtistAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-name-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + context.Artists.Add(existingArtist); + await context.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasAnArtistWithTheSameName_ShouldPersistTheArtist() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), name: "Queen", includeAlbums: false, includeContributors: false); + context.Artists.Add(existingArtist); + await context.SaveChangesAsync(); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + ArtistEntity? storedArtist = await context.Artists.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + Assert.Equal(libraryId, storedArtist!.LibraryId); + } + + [Fact] + public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-duprequest-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + album.Tracks = + [ + _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false), + _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false) + ]; + artist.Albums = [album]; + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-storedpath-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity existingArtist = await SeedArtistAsync(context, libraryId, "Existing"); + AlbumEntity existingAlbum = await SeedAlbumAsync(context, libraryId, existingArtist.Id); + context.Tracks.Add(_trackEntityFixture.Create( + albumId: existingAlbum.Id, libraryId: libraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false)); + await context.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false)]; + artist.Albums = [album]; + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheArtist() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-otherlibrarypath-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid firstLibraryId = Guid.NewGuid(); + ArtistEntity firstArtist = await SeedArtistAsync(context, firstLibraryId, "First"); + AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId, firstArtist.Id); + context.Tracks.Add(_trackEntityFixture.Create( + albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)); + await context.SaveChangesAsync(); + + Guid secondLibraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: secondLibraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: secondLibraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: secondLibraryId, path: "/music/queen/we-are-the-champions.flac", includeMetadata: false)]; + artist.Albums = [album]; + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + ArtistEntity? storedArtist = await context.Artists.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + Assert.Equal(secondLibraryId, storedArtist!.LibraryId); + } + + [Fact] + public async Task InsertAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-reuse-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + context.Set().Add(_tagEntityFixture.Create(name: "ExistingTag")); + context.Set().Add(_genreEntityFixture.Create(name: "ExistingGenre")); + await context.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + album.Tracks = [track]; + artist.Albums = [album]; + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + // The shared rows are reused instead of being duplicated. + Assert.Single(await context.Set().Where(tag => tag.Name == "ExistingTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "ExistingGenre").ToListAsync()); + } + + [Fact] + public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldPersistItOnce() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-insert-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + album.Tracks = [track]; + artist.Albums = [album]; + + // Act + Result result = await sut.InsertAsync(artist, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The name shared by the album and its tracks is persisted exactly once. + Assert.Single(await context.Set().Where(tag => tag.Name == "SharedNewTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "SharedNewGenre").ToListAsync()); + } + + [Fact] + public async Task UpdateAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTrack_ShouldPersistItOnce() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-shared-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + album.Tags = []; + album.Genres = []; + track.Tags = []; + track.Genres = []; + album.Tracks = [track]; + artist.Albums = [album]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + AlbumEntity incomingAlbum = Assert.Single(incoming.Albums); + TrackEntity incomingTrack = Assert.Single(incomingAlbum.Tracks); + incomingAlbum.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + incomingAlbum.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + incomingTrack.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + incomingTrack.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + // The name shared by the album and its track is persisted exactly once. + Assert.Single(await context.Set().Where(tag => tag.Name == "SharedNewTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "SharedNewGenre").ToListAsync()); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Contributors = + [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "NoopAlbumTag")]; + album.Genres = [_genreEntityFixture.Create(name: "NoopAlbumGenre")]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "NoopTrackTag")]; + track.Genres = [_genreEntityFixture.Create(name: "NoopTrackGenre")]; + album.Tracks = [track]; + artist.Albums = [album]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + Guid contributorId = artist.Contributors[0].Id; + DateTime contributorCreatedOnUtc = artist.Contributors[0].CreatedOnUtc; + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? storedArtist = await context.Artists + .AsNoTracking() + .Include(candidate => candidate.Contributors) + .Include(candidate => candidate.Albums) + .ThenInclude(candidate => candidate.Tracks) + .AsSplitQuery() + .FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + Assert.Null(storedArtist!.UpdatedOnUtc); + ArtistContributorEntity storedContributor = Assert.Single(storedArtist.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + // The tag and genre rows of the album and its track are left untouched. + Assert.Single(await context.Set().Where(tag => tag.Name == "NoopAlbumTag").ToListAsync()); + Assert.Single(await context.Set().Where(tag => tag.Name == "NoopTrackTag").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "NoopAlbumGenre").ToListAsync()); + Assert.Single(await context.Set().Where(genre => genre.Name == "NoopTrackGenre").ToListAsync()); + } + + [Fact] + public async Task UpdateAsync_WhenOnlyTheScalarValuesChanged_ShouldStampTheArtistAndKeepChildIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-scalars-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Contributors = + [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + Guid contributorId = artist.Contributors[0].Id; + DateTime contributorCreatedOnUtc = artist.Contributors[0].CreatedOnUtc; + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + incoming.Name = "Freddie Mercury"; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? storedArtist = await context.Artists.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + Assert.Equal("Freddie Mercury", storedArtist!.Name); + // Only the edited artist is stamped, the child rows keep their identity and their audit columns. + Assert.Equal(utcNow, storedArtist.UpdatedOnUtc); + Assert.Equal(userId, storedArtist.UpdatedBy); + ArtistContributorEntity storedContributor = Assert.Single(storedArtist.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid keptMediaContributorId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + ArtistContributorEntity keptContributor = _artistContributorEntityFixture.Create( + artistId: artist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + ArtistContributorEntity removedContributor = _artistContributorEntityFixture.Create( + artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Composer); + artist.Contributors = [keptContributor, removedContributor]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set() + .AsNoTracking() + .Where(contributor => contributor.ArtistId == artist.Id) + .ToListAsync(); + ArtistContributorEntity storedContributor = Assert.Single(storedContributors); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenAnAlbumAndItsTrackAreAdded_ShouldPersistThem() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-addalbum-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + AlbumEntity addedAlbum = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + addedAlbum.Tracks = + [_trackEntityFixture.Create(albumId: addedAlbum.Id, libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false)]; + incoming.Albums = [addedAlbum]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? storedAlbum = await context.Albums.AsNoTracking().Include(album => album.Tracks).FirstOrDefaultAsync(album => album.Id == addedAlbum.Id); + Assert.NotNull(storedAlbum); + TrackEntity storedTrack = Assert.Single(storedAlbum!.Tracks); + Assert.Equal("/music/queen/love-of-my-life.flac", storedTrack.Path); + } + + [Fact] + public async Task UpdateAsync_WhenANewTrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-dup-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id); + context.Tracks.Add(_trackEntityFixture.Create( + albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)); + await context.SaveChangesAsync(); + + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + AlbumEntity incomingAlbum = incoming.Albums.Single(); + TrackEntity addedTrack = _trackEntityFixture.Create( + albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + incomingAlbum.Tracks.Add(addedTrack); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + Assert.Equal(1, await context.Tracks.CountAsync(candidate => candidate.LibraryId == libraryId)); + } + + [Fact] + public async Task DeleteByIdAsync_WhenArtistExists_ShouldDeleteTheArtistAndItsChildren() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-delete-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + AlbumEntity album = await SeedAlbumAsync(context, libraryId, artist.Id); + context.Tracks.Add(_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false)); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.DeleteByIdAsync(artist.Id, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + Assert.Null(await context.Artists.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == artist.Id)); + Assert.Empty(await context.Albums.AsNoTracking().Where(candidate => candidate.ArtistId == artist.Id).ToListAsync()); + Assert.Empty(await context.Tracks.AsNoTracking().Where(candidate => candidate.LibraryId == libraryId).ToListAsync()); + } + + [Fact] + public async Task GetByIdAsync_WhenArtistExists_ShouldIncludeTheNavigationProperties() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedFullArtistAsync(context, libraryId); + + // Act + Result result = await sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity retrievedArtist = result.Value!; + Assert.Single(retrievedArtist.Contributors); + AlbumEntity retrievedAlbum = Assert.Single(retrievedArtist.Albums); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Single(retrievedTrack.Ratings); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Equal(2, retrievedTrack.Isrcs.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedArtist() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen"); + context.ChangeTracker.Clear(); + + // Act + Result result = await sut.GetByIdAsync( + artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Empty(context.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnOnlyTheLibraryArtistsWithPagination() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(3); + foreach (ArtistEntity artist in artists) + { + artist.LibraryId = libraryId; + artist.Albums = []; + artist.Contributors = []; + } + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + context.Artists.AddRange(artists); + context.Artists.Add(artistOfAnotherLibrary); + await context.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count); + Assert.Equal(3, result.Value.Data.Count); + Assert.DoesNotContain(result.Value.Data, artist => artist.Id == artistOfAnotherLibrary.Id); + } + + [Fact] + public async Task GetAllAsync_WhenTheSearchTermDiffersInCase_ShouldMatchCaseInsensitively() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-search-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity matchingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistEntity otherArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Radiohead", includeAlbums: false, includeContributors: false); + context.Artists.AddRange(matchingArtist, otherArtist); + await context.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "QUEENS"); + + // Act + Result> result = await sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity retrievedArtist = Assert.Single(result.Value.Data); + Assert.Equal(matchingArtist.Id, retrievedArtist.Id); + } + + [Fact] + public async Task GetAllAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnUntrackedArtists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getall-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + context.Artists.Add(artist); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await sut.GetAllAsync( + null, null, null, filter, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value.Data); + Assert.Empty(context.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnTheArtistLiteRowsOrdered() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-lite-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + context.Artists.AddRange(betaArtist, alphaArtist); + await context.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([alphaArtist.Id, betaArtist.Id], result.Value.Data.Select(row => row.Id)); + Assert.Equal([alphaArtist.Name, betaArtist.Name], result.Value.Data.Select(row => row.Name)); + Assert.Equal(2, result.Value.Count); + Assert.Equal(1, result.Value.CurrentPage); + Assert.Equal(2, result.Value.PerPage); + } + + [Fact] + public async Task GetAllLiteAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnUntrackedRows() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-getalllite-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + context.Artists.Add(artist); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value.Data); + Assert.Empty(context.ChangeTracker.Entries()); + } + + [Fact] + public async Task UpdateAsync_WhenManyTracksAreUpdated_ShouldNotReloadEachTrackIndividually() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-queries-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + SelectCountingInterceptor interceptor = new(); + using LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(interceptor) + .Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid smallLibraryId = Guid.NewGuid(); + ArtistEntity smallArtist = SeedArtistWithAlbums(context, smallLibraryId, albumCount: 1, tracksPerAlbum: 1); + await context.SaveChangesAsync(); + + Guid largeLibraryId = Guid.NewGuid(); + ArtistEntity largeArtist = SeedArtistWithAlbums(context, largeLibraryId, albumCount: 4, tracksPerAlbum: 10); + await context.SaveChangesAsync(); + + ArtistEntity smallIncoming = await LoadDetachedArtistAsync(context, smallArtist.Id); + ArtistEntity largeIncoming = await LoadDetachedArtistAsync(context, largeArtist.Id); + + // Act + interceptor.Reset(); + Result smallResult = await sut.UpdateAsync(smallIncoming, CancellationToken.None); + await context.SaveChangesAsync(); + int smallSelectCount = interceptor.SelectCount; + + interceptor.Reset(); + Result largeResult = await sut.UpdateAsync(largeIncoming, CancellationToken.None); + await context.SaveChangesAsync(); + int largeSelectCount = interceptor.SelectCount; + + // Assert + Assert.False(smallResult.IsFailure); + Assert.False(largeResult.IsFailure); + // The artist aggregate is loaded once and the children are applied to the already tracked instances, so the number of read queries + // does not grow with the number of albums or tracks of the aggregate. + Assert.True(largeSelectCount <= smallSelectCount + 2, $"The large aggregate issued {largeSelectCount} read queries, while the small aggregate issued {smallSelectCount}."); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateAnyReconciledChildCollection() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-noop-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Contributors = + [ + _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals), + _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer) + ]; + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: $"noop-album-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-album-tag-two-{Guid.NewGuid():N}")]; + album.Genres = [_genreEntityFixture.Create(name: $"noop-album-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-album-genre-two-{Guid.NewGuid():N}")]; + album.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10) + ]; + album.Contributors = + [ + _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer), + _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Composer) + ]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: $"noop-track-tag-{Guid.NewGuid():N}"), _tagEntityFixture.Create(name: $"noop-track-tag-two-{Guid.NewGuid():N}")]; + track.Genres = [_genreEntityFixture.Create(name: $"noop-track-genre-{Guid.NewGuid():N}"), _genreEntityFixture.Create(name: $"noop-track-genre-two-{Guid.NewGuid():N}")]; + track.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.User, voteCount: 20) + ]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + track.Contributors = + [ + _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals), + _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer) + ]; + album.Tracks = [track]; + artist.Albums = [album]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + // Detach the seeded graph, so that the update must load the tracked aggregate through its include chain instead of returning the already populated seeded instances. + context.ChangeTracker.Clear(); + + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? storedArtist = await context.Artists.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + Assert.Equal(2, storedArtist!.Contributors.Count); + AlbumEntity? storedAlbum = await context.Albums + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Equal(2, storedAlbum!.Tags.Count); + Assert.Equal(2, storedAlbum.Genres.Count); + Assert.Equal(2, storedAlbum.Ratings.Count); + Assert.Equal(2, storedAlbum.Contributors.Count); + TrackEntity? storedTrack = await context.Tracks + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Moods) + .Include(candidate => candidate.Isrcs) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal(2, storedTrack!.Tags.Count); + Assert.Equal(2, storedTrack.Genres.Count); + Assert.Equal(2, storedTrack.Ratings.Count); + Assert.Equal(2, storedTrack.Moods.Count); + Assert.Equal(2, storedTrack.Isrcs.Count); + Assert.Equal(2, storedTrack.Contributors.Count); + } + + [Fact] + public async Task UpdateAsync_WhenOneItemIsRemovedFromEachReconciledChildCollection_ShouldRemoveOnlyThoseItems() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-artistrepo-update-remove-collections-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ArtistRepository sut = CreateArtistRepository(context); + + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistContributorEntity keptArtistContributor = _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals); + artist.Contributors = [keptArtistContributor, _artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + + string keptAlbumTagName = $"remove-album-tag-{Guid.NewGuid():N}"; + string keptAlbumGenreName = $"remove-album-genre-{Guid.NewGuid():N}"; + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: keptAlbumTagName), _tagEntityFixture.Create(name: $"remove-album-tag-two-{Guid.NewGuid():N}")]; + album.Genres = [_genreEntityFixture.Create(name: keptAlbumGenreName), _genreEntityFixture.Create(name: $"remove-album-genre-two-{Guid.NewGuid():N}")]; + album.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10) + ]; + AlbumContributorEntity keptAlbumContributor = _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer); + album.Contributors = [keptAlbumContributor, _albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Composer)]; + + string keptTrackTagName = $"remove-track-tag-{Guid.NewGuid():N}"; + string keptTrackGenreName = $"remove-track-genre-{Guid.NewGuid():N}"; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: keptTrackTagName), _tagEntityFixture.Create(name: $"remove-track-tag-two-{Guid.NewGuid():N}")]; + track.Genres = [_genreEntityFixture.Create(name: keptTrackGenreName), _genreEntityFixture.Create(name: $"remove-track-genre-two-{Guid.NewGuid():N}")]; + track.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.User, voteCount: 20) + ]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + TrackContributorEntity keptTrackContributor = _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals); + track.Contributors = [keptTrackContributor, _trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + album.Tracks = [track]; + artist.Albums = [album]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + // Detach the seeded graph, so that the update must load the tracked aggregate through its include chain instead of returning the already populated seeded instances. + context.ChangeTracker.Clear(); + + ArtistEntity incoming = await LoadDetachedArtistAsync(context, artist.Id); + AlbumEntity incomingAlbum = Assert.Single(incoming.Albums); + TrackEntity incomingTrack = Assert.Single(incomingAlbum.Tracks); + incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.Id == keptArtistContributor.Id)]; + incomingAlbum.Tags = [incomingAlbum.Tags.Single(tag => tag.Name == keptAlbumTagName)]; + incomingAlbum.Genres = [incomingAlbum.Genres.Single(genre => genre.Name == keptAlbumGenreName)]; + incomingAlbum.Ratings = [incomingAlbum.Ratings.Single(rating => rating.Source == AudioRatingSource.MusicBrainz)]; + incomingAlbum.Contributors = [incomingAlbum.Contributors.Single(contributor => contributor.Id == keptAlbumContributor.Id)]; + incomingTrack.Tags = [incomingTrack.Tags.Single(tag => tag.Name == keptTrackTagName)]; + incomingTrack.Genres = [incomingTrack.Genres.Single(genre => genre.Name == keptTrackGenreName)]; + incomingTrack.Ratings = [incomingTrack.Ratings.Single(rating => rating.Source == AudioRatingSource.MusicBrainz)]; + incomingTrack.Moods = [incomingTrack.Moods.Single(mood => mood.Name == "Calm")]; + incomingTrack.Isrcs = [incomingTrack.Isrcs.Single(isrc => isrc.Value == "USRC12345678")]; + incomingTrack.Contributors = [incomingTrack.Contributors.Single(contributor => contributor.Id == keptTrackContributor.Id)]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? storedArtist = await context.Artists.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == artist.Id); + Assert.NotNull(storedArtist); + ArtistContributorEntity storedArtistContributor = Assert.Single(storedArtist!.Contributors); + Assert.Equal(keptArtistContributor.Id, storedArtistContributor.Id); + AlbumEntity? storedAlbum = await context.Albums + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == album.Id); + Assert.NotNull(storedAlbum); + Assert.Equal(keptAlbumTagName, Assert.Single(storedAlbum!.Tags).Name); + Assert.Equal(keptAlbumGenreName, Assert.Single(storedAlbum.Genres).Name); + Assert.Equal(AudioRatingSource.MusicBrainz, Assert.Single(storedAlbum.Ratings).Source); + Assert.Equal(keptAlbumContributor.Id, Assert.Single(storedAlbum.Contributors).Id); + TrackEntity? storedTrack = await context.Tracks + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Moods) + .Include(candidate => candidate.Isrcs) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal(keptTrackTagName, Assert.Single(storedTrack!.Tags).Name); + Assert.Equal(keptTrackGenreName, Assert.Single(storedTrack.Genres).Name); + Assert.Equal(AudioRatingSource.MusicBrainz, Assert.Single(storedTrack.Ratings).Source); + Assert.Equal("Calm", Assert.Single(storedTrack.Moods).Name); + Assert.Equal("USRC12345678", Assert.Single(storedTrack.Isrcs).Value); + Assert.Equal(keptTrackContributor.Id, Assert.Single(storedTrack.Contributors).Id); + } + + /// + /// Seeds an artist that owns the requested number of albums, each with the requested number of tracks, all of them with distinct shared reference names. + /// + /// The context the artist is persisted through. + /// The Id of the library that owns the artist. + /// The number of albums the artist owns. + /// The number of tracks each album owns. + /// The created artist. + private ArtistEntity SeedArtistWithAlbums(LuminaDbContext context, Guid libraryId, int albumCount, int tracksPerAlbum) + { + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + List albums = []; + for (int albumIndex = 0; albumIndex < albumCount; albumIndex++) + { + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: $"album-tag-{libraryId:N}-{albumIndex}")]; + album.Genres = [_genreEntityFixture.Create(name: $"album-genre-{libraryId:N}-{albumIndex}")]; + List tracks = []; + for (int trackIndex = 0; trackIndex < tracksPerAlbum; trackIndex++) + { + TrackEntity track = _trackEntityFixture.Create( + albumId: album.Id, libraryId: libraryId, path: $"/music/{libraryId:N}/track-{albumIndex}-{trackIndex}.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: $"track-tag-{libraryId:N}-{albumIndex}-{trackIndex}")]; + track.Genres = [_genreEntityFixture.Create(name: $"track-genre-{libraryId:N}-{albumIndex}-{trackIndex}")]; + tracks.Add(track); + } + album.Tracks = tracks; + albums.Add(album); + } + artist.Albums = albums; + context.Artists.Add(artist); + return artist; + } + + /// + /// Creates an artist repository backed by the provided context, wiring the real album and track repositories. + /// + /// The context the repository operates on. + /// The created repository. + private static ArtistRepository CreateArtistRepository(LuminaDbContext context) + { + TrackRepository trackRepository = new(context); + AlbumRepository albumRepository = new(context, trackRepository); + return new ArtistRepository(context, albumRepository, trackRepository); + } + + /// + /// Seeds an artist with no albums or contributors. + /// + /// The context the artist is persisted through. + /// The Id of the library that owns the artist. + /// The name of the artist. + /// The persisted artist. + private async Task SeedArtistAsync(LuminaDbContext context, Guid libraryId, string name) + { + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false); + context.Artists.Add(artist); + await context.SaveChangesAsync(); + return artist; + } + + /// + /// Seeds an artist with one album and one track, including every related collection deterministically. + /// + /// The context the artist is persisted through. + /// The Id of the library that owns the artist. + /// The persisted artist. + private async Task SeedFullArtistAsync(LuminaDbContext context, Guid libraryId) + { + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Contributors = + [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + album.Tags = [_tagEntityFixture.Create(name: "album-tag-1"), _tagEntityFixture.Create(name: "album-tag-2")]; + album.Genres = [_genreEntityFixture.Create(name: "album-genre-1"), _genreEntityFixture.Create(name: "album-genre-2")]; + album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)]; + track.Tags = [_tagEntityFixture.Create(name: "track-tag-1"), _tagEntityFixture.Create(name: "track-tag-2")]; + track.Genres = [_genreEntityFixture.Create(name: "track-genre-1"), _genreEntityFixture.Create(name: "track-genre-2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + album.Tracks = [track]; + artist.Albums = [album]; + context.Artists.Add(artist); + await context.SaveChangesAsync(); + return artist; + } + + /// + /// Seeds an album that belongs to the artist identified by . + /// + /// The context the album is persisted through. + /// The Id of the library that owns the album. + /// The Id of the artist that owns the album. + /// The persisted album. + private async Task SeedAlbumAsync(LuminaDbContext context, Guid libraryId, Guid artistId) + { + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: false); + context.Albums.Add(album); + await context.SaveChangesAsync(); + return album; + } + + /// + /// Loads a detached copy of a stored artist with the whole aggregate, so that it can be handed to the repository as the desired state of an edit. + /// + /// The context that tracks the stored artist. + /// The Id of the artist to load. + /// The detached copy of the artist. + private static async Task LoadDetachedArtistAsync(LuminaDbContext context, Guid artistId) + { + return await context.Artists + .AsNoTracking() + .Include(artist => artist.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Ratings) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tags) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Genres) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Contributors) + .Include(artist => artist.Albums) + .ThenInclude(album => album.Tracks) + .ThenInclude(track => track.Ratings) + .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.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) + .AsSplitQuery() + .FirstAsync(artist => artist.Id == artistId); + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Counts the number of read commands issued through a context, so that tests can assert that the number of queries does not scale with the aggregate size. + /// + private sealed class SelectCountingInterceptor : DbCommandInterceptor + { + /// + /// Gets the number of SELECT commands observed since the last reset. + /// + public int SelectCount { get; private set; } + + /// + /// Resets the observed command count. + /// + public void Reset() + { + SelectCount = 0; + } + + /// + /// Counts the command before it is executed synchronously. + /// + /// The command that is about to be executed. + /// The event data of the command. + /// The interception result. + /// The interception result, unmodified. + public override InterceptionResult ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult result) + { + CountIfSelect(command); + return base.ReaderExecuting(command, eventData, result); + } + + /// + /// Counts the command before it is executed asynchronously. + /// + /// The command that is about to be executed. + /// The event data of the command. + /// The interception result. + /// Cancellation token that can be used to stop the execution. + /// The interception result, unmodified. + public override ValueTask> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + CountIfSelect(command); + return base.ReaderExecutingAsync(command, eventData, result, cancellationToken); + } + + /// + /// Increments the count when is a SELECT statement. + /// + /// The command to inspect. + private void CountIfSelect(DbCommand command) + { + if (command.CommandText.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)) + SelectCount++; + } + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs new file mode 100644 index 00000000..0d0279c9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs @@ -0,0 +1,751 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +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.DTO.Pagination; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +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.MediaContributors; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +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.DataAccess.IntegrationTests.Core.Repositories.MusicLibrary; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class TrackRepositoryTests +{ + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + [Fact] + public async Task InsertAsync_WhenCalledWithAValidTrack_ShouldPersistTheTrackAndItsChildren() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + MediaContributorEntity performer = _mediaContributorEntityFixture.Create(displayName: $"Performer {Guid.NewGuid()}"); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "InsertTag")]; + track.Genres = [_genreEntityFixture.Create(name: "InsertGenre")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)]; + + // Act + Result result = await sut.InsertAsync(track, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + TrackEntity? storedTrack = await context.Tracks + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .Include(candidate => candidate.Moods) + .Include(candidate => candidate.Isrcs) + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Contributors) + .FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal("/music/queen/bohemian-rhapsody.flac", storedTrack!.Path); + Assert.Single(storedTrack.Tags); + Assert.Single(storedTrack.Genres); + Assert.Single(storedTrack.Moods); + Assert.Single(storedTrack.Isrcs); + Assert.Single(storedTrack.Ratings); + TrackContributorEntity storedContributor = Assert.Single(storedTrack.Contributors); + Assert.Equal(performer.Id, storedContributor.MediaContributorId); + } + + [Fact] + public async Task InsertAsync_WhenAnotherTrackOfTheSameLibraryHasTheSamePath_ShouldReturnTrackAlreadyExists() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-conflict-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity existingTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false); + context.Tracks.Add(existingTrack); + await context.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false); + + // Act + Result result = await sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldPersistTheTrack() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-insert-otherlibrary-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid firstLibraryId = Guid.NewGuid(); + AlbumEntity firstAlbum = await SeedAlbumAsync(context, firstLibraryId); + TrackEntity existingTrack = _trackEntityFixture.Create(albumId: firstAlbum.Id, libraryId: firstLibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false); + context.Tracks.Add(existingTrack); + await context.SaveChangesAsync(); + + Guid secondLibraryId = Guid.NewGuid(); + AlbumEntity secondAlbum = await SeedAlbumAsync(context, secondLibraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: secondAlbum.Id, libraryId: secondLibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false); + + // Act + Result result = await sut.InsertAsync(track, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + TrackEntity? storedTrack = await context.Tracks.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal(secondLibraryId, storedTrack!.LibraryId); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenCalled_ShouldReturnOnlyThePathsOfTheLibraryCaseSensitively() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-existingpaths-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity trackOfLibrary = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/Queen/Love-Of-My-Life.flac", includeMetadata: false); + context.Tracks.Add(trackOfLibrary); + + Guid anotherLibraryId = Guid.NewGuid(); + AlbumEntity anotherAlbum = await SeedAlbumAsync(context, anotherLibraryId); + TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(albumId: anotherAlbum.Id, libraryId: anotherLibraryId, path: "/music/Queen/Love-Of-My-Life.flac", includeMetadata: false); + context.Tracks.Add(trackOfAnotherLibrary); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetExistingPathsAsync( + libraryId, ["/music/Queen/Love-Of-My-Life.flac", "/music/queen/love-of-my-life.flac", "/music/queen/we-are-the-champions.flac"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + string existingPath = Assert.Single(result.Value); + // The comparison is ordinal, so neither the same path of another library nor a case variant of the path is reported as existing. + Assert.Equal("/music/Queen/Love-Of-My-Life.flac", existingPath); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotChangeAnyAuditColumn() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + MediaContributorEntity performer = _mediaContributorEntityFixture.Create(displayName: $"Performer {Guid.NewGuid()}"); + context.MediaContributors.Add(performer); + await context.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/dont-stop-me-now.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "NoopTag")]; + track.Genres = [_genreEntityFixture.Create(name: "NoopGenre")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + track.Contributors = + [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + // Detach the seeded graph, so that the update must load the tracked track through its include chain instead of returning the already populated seeded instance. + context.ChangeTracker.Clear(); + Guid contributorId = track.Contributors[0].Id; + DateTime contributorCreatedOnUtc = track.Contributors[0].CreatedOnUtc; + TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? storedTrack = await context.Tracks.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Null(storedTrack!.UpdatedOnUtc); + TrackContributorEntity storedContributor = Assert.Single(storedTrack.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + Assert.Single(context.Set().Where(tag => tag.Name == "NoopTag")); + Assert.Single(context.Set().Where(genre => genre.Name == "NoopGenre")); + } + + [Fact] + public async Task UpdateAsync_WhenOnlyTheMetadataChanged_ShouldStampTheTrackAndKeepTheChildRowsUntouched() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-metadata-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + MediaContributorEntity performer = _mediaContributorEntityFixture.Create(displayName: $"Performer {Guid.NewGuid()}"); + context.MediaContributors.Add(performer); + await context.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/somebody-to-love.flac", includeMetadata: false); + track.Contributors = + [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: performer.Id, role: MediaContributorRole.Vocals)]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + Guid contributorId = track.Contributors[0].Id; + DateTime contributorCreatedOnUtc = track.Contributors[0].CreatedOnUtc; + TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id); + incoming.Title = "Somebody to Love"; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? storedTrack = await context.Tracks.AsNoTracking().Include(candidate => candidate.Contributors).FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal("Somebody to Love", storedTrack!.Title); + // Only the edited track is stamped, the child rows keep their identity and their audit columns. + Assert.Equal(utcNow, storedTrack.UpdatedOnUtc); + Assert.Equal(userId, storedTrack.UpdatedBy); + TrackContributorEntity storedContributor = Assert.Single(storedTrack.Contributors); + Assert.Equal(contributorId, storedContributor.Id); + Assert.Equal(contributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsRemoved_ShouldDeleteOnlyThatParticipationAndKeepTheOtherIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-removecontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + Guid keptMediaContributorId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/another-one-bites-the-dust.flac", includeMetadata: false); + TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create( + trackId: track.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer); + TrackContributorEntity removedContributor = _trackContributorEntityFixture.Create( + trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer); + track.Contributors = [keptContributor, removedContributor]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id); + incoming.Contributors = [incoming.Contributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId)]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set() + .AsNoTracking() + .Where(contributor => contributor.TrackId == track.Id) + .ToListAsync(); + TrackContributorEntity storedContributor = Assert.Single(storedContributors); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptMediaContributorId, storedContributor.MediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenAContributorIsAdded_ShouldInsertOnlyTheNewParticipationAndKeepTheExistingIdentity() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-addcontributor-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + Guid keptMediaContributorId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/crazy-little-thing-called-love.flac", includeMetadata: false); + TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create( + trackId: track.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer); + track.Contributors = [keptContributor]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + Guid keptContributorId = keptContributor.Id; + Guid addedMediaContributorId = Guid.NewGuid(); + + TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id); + incoming.Contributors.Add(_trackContributorEntityFixture.Create( + trackId: track.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals)); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await context.Set() + .AsNoTracking() + .Where(contributor => contributor.TrackId == track.Id) + .ToListAsync(); + Assert.Equal(2, storedContributors.Count); + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-tags-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/radio-ga-ga.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id); + incoming.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + incoming.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? storedTrack = await context.Tracks + .AsNoTracking() + .Include(candidate => candidate.Tags) + .Include(candidate => candidate.Genres) + .FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal("ExistingTag", Assert.Single(storedTrack!.Tags).Name); + Assert.Equal("ExistingGenre", Assert.Single(storedTrack.Genres).Name); + // The shared rows are reused instead of being duplicated by the update. + Assert.Single(context.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(context.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task UpdateAsync_WhenOwnedAudioCollectionsChange_ShouldReconcileRatingsMoodsAndIsrcs() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-update-owned-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/the-show-must-go-on.flac", includeMetadata: false); + track.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20) + ]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Energetic")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + TrackEntity incoming = await LoadDetachedTrackAsync(context, track.Id); + incoming.Ratings = + [ + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5) + ]; + incoming.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + incoming.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000002")]; + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? storedTrack = await context.Tracks + .AsNoTracking() + .Include(candidate => candidate.Ratings) + .Include(candidate => candidate.Moods) + .Include(candidate => candidate.Isrcs) + .FirstOrDefaultAsync(candidate => candidate.Id == track.Id); + Assert.NotNull(storedTrack); + Assert.Equal(3, storedTrack!.Ratings.Count); + Assert.Contains(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M); + Assert.Contains(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M); + Assert.Contains(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M); + Assert.DoesNotContain(storedTrack.Ratings, rating => rating.Source == AudioRatingSource.LastFm); + Assert.Equal(2, storedTrack.Moods.Count); + Assert.Single(storedTrack.Moods, mood => mood.Name == "Calm"); + Assert.Contains(storedTrack.Moods, mood => mood.Name == "Upbeat"); + Assert.Equal(2, storedTrack.Isrcs.Count); + Assert.Single(storedTrack.Isrcs, isrc => isrc.Value == "USRC12345678"); + Assert.Contains(storedTrack.Isrcs, isrc => isrc.Value == "GBAYE0000002"); + } + + [Fact] + public async Task GetByIdAsync_WhenTrackExists_ShouldIncludeTheNavigationProperties() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + ArtistEntity artist = await context.Artists.AsNoTracking().FirstAsync(candidate => candidate.Id == album.ArtistId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/killer-queen.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + track.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + context.Tracks.Add(track); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + TrackEntity retrievedTrack = result.Value!; + Assert.NotNull(retrievedTrack.Album); + Assert.Equal(album.Id, retrievedTrack.Album!.Id); + Assert.NotNull(retrievedTrack.Album.Artist); + Assert.Equal(artist.Id, retrievedTrack.Album.Artist!.Id); + Assert.Equal(2, retrievedTrack.Tags.Count); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Single(retrievedTrack.Isrcs); + Assert.Single(retrievedTrack.Ratings); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetByIdAsync_WhenEntitiesShouldNotBeTracked_ShouldReturnAnUntrackedTrack() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyid-notracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/seven-seas-of-rhye.flac", includeMetadata: false); + context.Tracks.Add(track); + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + + // Act + Result result = await sut.GetByIdAsync( + track.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Empty(context.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenCalled_ShouldReturnTheAlbumTracksInOrderWithTheirCollections() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-getbyalbum-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + TrackEntity secondDiscTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/stone-cold-crazy.flac", trackNumber: 1, includeMetadata: false); + secondDiscTrack.DiscNumber = 2; + TrackEntity firstDiscSecondTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/good-old-fashioned-lover-boy.flac", trackNumber: 2, includeMetadata: false); + firstDiscSecondTrack.DiscNumber = 1; + TrackEntity firstDiscFirstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/tie-your-mother-down.flac", trackNumber: 1, includeMetadata: false); + firstDiscFirstTrack.DiscNumber = 1; + firstDiscFirstTrack.Tags = [_tagEntityFixture.Create(name: "OrderedTag")]; + firstDiscFirstTrack.Genres = [_genreEntityFixture.Create(name: "OrderedGenre")]; + firstDiscFirstTrack.Moods = [_trackMoodEntityFixture.Create(name: "Calm")]; + firstDiscFirstTrack.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; + firstDiscFirstTrack.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + firstDiscFirstTrack.Contributors = [_trackContributorEntityFixture.Create(trackId: firstDiscFirstTrack.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + context.Tracks.AddRange(secondDiscTrack, firstDiscSecondTrack, firstDiscFirstTrack); + + AlbumEntity anotherAlbum = await SeedAlbumAsync(context, libraryId); + TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(albumId: anotherAlbum.Id, libraryId: libraryId, path: "/music/queen/play-the-game.flac", includeMetadata: false); + context.Tracks.Add(trackOfAnotherAlbum); + await context.SaveChangesAsync(); + + List albumTracks = [firstDiscFirstTrack, firstDiscSecondTrack, secondDiscTrack]; + Guid[] expectedOrder = [.. albumTracks + .OrderBy(track => track.DiscNumber) + .ThenBy(track => track.TrackNumber) + .ThenBy(track => track.Id) + .Select(track => track.Id)]; + + // Act + Result> result = await sut.GetByAlbumIdAsync(album.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Select(track => track.Id)); + Assert.DoesNotContain(result.Value, track => track.Id == trackOfAnotherAlbum.Id); + TrackEntity retrievedTrack = result.Value.First(track => track.Id == firstDiscFirstTrack.Id); + Assert.Single(retrievedTrack.Tags); + Assert.Single(retrievedTrack.Genres); + Assert.Single(retrievedTrack.Moods); + Assert.Single(retrievedTrack.Isrcs); + Assert.Single(retrievedTrack.Ratings); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetTracksLiteByAlbumIdAsync_WhenPaginationDataIsNull_ShouldReturnAllTracksOfTheAlbum() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-lite-null-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + List tracks = _trackEntityFixture.CreateMany(3); + for (int index = 0; index < tracks.Count; index++) + { + tracks[index].AlbumId = album.Id; + tracks[index].LibraryId = libraryId; + tracks[index].Path = $"/music/queen/track-{index}.flac"; + tracks[index].DiscNumber = 1; + tracks[index].TrackNumber = index + 1; + tracks[index].Tags = []; + tracks[index].Genres = []; + tracks[index].Moods = []; + tracks[index].Isrcs = []; + tracks[index].Ratings = []; + tracks[index].Contributors = []; + } + context.Tracks.AddRange(tracks); + + AlbumEntity anotherAlbum = await SeedAlbumAsync(context, libraryId); + TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(albumId: anotherAlbum.Id, libraryId: libraryId, path: "/music/queen/save-me.flac", includeMetadata: false); + context.Tracks.Add(trackOfAnotherAlbum); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetTracksLiteByAlbumIdAsync(album.Id, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(3, page.Count); + Assert.Equal(3, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(3, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + Assert.DoesNotContain(page.Data, row => row.Id == trackOfAnotherAlbum.Id); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetTracksLiteByAlbumIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage( + int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-lite-page-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + TrackRepository sut = new(context); + + Guid libraryId = Guid.NewGuid(); + AlbumEntity album = await SeedAlbumAsync(context, libraryId); + List tracks = _trackEntityFixture.CreateMany(5); + for (int index = 0; index < tracks.Count; index++) + { + tracks[index].AlbumId = album.Id; + tracks[index].LibraryId = libraryId; + tracks[index].Path = $"/music/queen/song-{index}.flac"; + tracks[index].DiscNumber = 1; + tracks[index].TrackNumber = index + 1; + tracks[index].Tags = []; + tracks[index].Genres = []; + tracks[index].Moods = []; + tracks[index].Isrcs = []; + tracks[index].Ratings = []; + tracks[index].Contributors = []; + } + context.Tracks.AddRange(tracks); + await context.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + + // Act + Result> result = await sut.GetTracksLiteByAlbumIdAsync(album.Id, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + /// + /// Seeds an artist and the album that owns the tracks of the library identified by , so that the required foreign keys of a track are satisfied. + /// + /// The context the artist and album are persisted through. + /// The Id of the library the album belongs to. + /// The persisted album. + private async Task SeedAlbumAsync(LuminaDbContext context, Guid libraryId) + { + ArtistEntity? artist = await context.Artists.FirstOrDefaultAsync(existing => existing.LibraryId == libraryId); + if (artist is null) + { + artist = _artistEntityFixture.Create( + libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + context.Artists.Add(artist); + await context.SaveChangesAsync(); + } + AlbumEntity album = _albumEntityFixture.Create( + artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + context.Albums.Add(album); + await context.SaveChangesAsync(); + return album; + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Loads a detached copy of a stored track, with its children, so that it can be handed to the repository as the desired state of an edit. + /// + /// The context that tracks the stored track. + /// The Id of the track to load. + /// The detached copy of the track. + private static async Task LoadDetachedTrackAsync(LuminaDbContext context, Guid trackId) + { + return await context.Tracks + .AsNoTracking() + .Include(track => track.Tags) + .Include(track => track.Genres) + .Include(track => track.Ratings) + .Include(track => track.Contributors) + .Include(track => track.Moods) + .Include(track => track.Isrcs) + .FirstAsync(track => track.Id == trackId); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs index d6fe1702..abb248ab 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs @@ -1,11 +1,15 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.DataAccess.Common.Interceptors; using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -30,7 +34,7 @@ public class ScheduledJobExecutionRepositoryTests // The deletion uses ExecuteDeleteAsync, which is not supported by the in-memory provider, so a real SQLite database is used. using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); ScheduledJobExecutionRepository sut = new(context); @@ -57,7 +61,7 @@ public class ScheduledJobExecutionRepositoryTests // Arrange using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); anchorConnection.Open(); - LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); context.Database.EnsureCreated(); ScheduledJobExecutionRepository sut = new(context); @@ -73,4 +77,68 @@ public class ScheduledJobExecutionRepositoryTests Assert.False(result.IsFailure); Assert.Equal(1, await context.ScheduledJobExecutions.CountAsync()); } + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheCreationColumnsAndStampTheModificationColumns() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobexecutionrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + ICurrentUserService currentUserService = Substitute.For(); + Guid actingUserId = Guid.NewGuid(); + currentUserService.UserId.Returns(actingUserId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + DateTime insertTimeUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + dateTimeProvider.UtcNow.Returns(insertTimeUtc); + // The context is built with the auditing interceptor attached, so an interceptor regression is caught instead of being masked by its absence. + using LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + ScheduledJobExecutionRepository sut = new(context); + + ScheduledJobExecutionEntity storedExecution = _scheduledJobExecutionEntityFixture.Create(isCycleRun: false); + context.ScheduledJobExecutions.Add(storedExecution); + await context.SaveChangesAsync(); + + // The interceptor stamps the creation columns on insert. + Assert.Equal(insertTimeUtc, storedExecution.CreatedOnUtc); + Assert.Equal(actingUserId, storedExecution.CreatedBy); + + DateTime updateTimeUtc = insertTimeUtc.AddDays(1); + dateTimeProvider.UtcNow.Returns(updateTimeUtc); + + ScheduledJobExecutionEntity updatedExecution = _scheduledJobExecutionEntityFixture.Create( + id: storedExecution.Id, + scheduledJobId: storedExecution.ScheduledJobId, + taskType: storedExecution.TaskType, + isCycleRun: true, + wasCycleActive: storedExecution.WasCycleActive, + startedOnUtc: storedExecution.StartedOnUtc, + completedOnUtc: DateTime.UtcNow); + // The incoming entity carries hostile audit values that must never win over the ones owned by the persistence medium. + updatedExecution.CreatedOnUtc = insertTimeUtc.AddYears(-10); + updatedExecution.CreatedBy = Guid.NewGuid(); + updatedExecution.UpdatedOnUtc = insertTimeUtc.AddYears(-5); + updatedExecution.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(updatedExecution, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + ScheduledJobExecutionEntity reloadedExecution = await context.ScheduledJobExecutions.AsNoTracking().FirstAsync(execution => execution.Id == storedExecution.Id); + Assert.True(reloadedExecution.IsCycleRun); + // The interceptor owns the modification columns and stamped them with the acting user and time, not with the incoming values. + Assert.Equal(updateTimeUtc, reloadedExecution.UpdatedOnUtc); + Assert.Equal(actingUserId, reloadedExecution.UpdatedBy); + // The creation columns are still the ones stamped on insert. + Assert.Equal(insertTimeUtc, reloadedExecution.CreatedOnUtc); + Assert.Equal(actingUserId, reloadedExecution.CreatedBy); + } } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs new file mode 100644 index 00000000..06c5fc56 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; +using Lumina.DataAccess.Core.Repositories.Scheduling; +using Lumina.DataAccess.Core.UoW; +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.Scheduling; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class ScheduledJobRepositoryTests +{ + private readonly ScheduledJobEntityFixture _scheduledJobEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-scheduledjobrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ScheduledJobRepository sut = new(context); + + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + ScheduledJobEntity storedJob = _scheduledJobEntityFixture.Create(name: "Original Job"); + storedJob.CreatedOnUtc = storedCreatedOnUtc; + storedJob.CreatedBy = storedCreatedBy; + context.ScheduledJobs.Add(storedJob); + await context.SaveChangesAsync(); + + ScheduledJobEntity updatedJob = _scheduledJobEntityFixture.Create( + id: storedJob.Id, + name: "Updated Job", + taskType: storedJob.TaskType, + scheduleType: storedJob.ScheduleType, + intervalMinutes: storedJob.IntervalMinutes, + hour: storedJob.Hour, + minute: storedJob.Minute, + status: storedJob.Status, + ownerUserId: storedJob.OwnerUserId, + lastStartedOnUtc: storedJob.LastStartedOnUtc, + lastCompletedOnUtc: storedJob.LastCompletedOnUtc); + updatedJob.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + updatedJob.CreatedBy = Guid.NewGuid(); + updatedJob.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5); + updatedJob.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(updatedJob, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + ScheduledJobEntity reloadedJob = await context.ScheduledJobs.AsNoTracking().FirstAsync(job => job.Id == storedJob.Id); + Assert.Equal("Updated Job", reloadedJob.Name); + Assert.Equal(storedCreatedOnUtc, reloadedJob.CreatedOnUtc); + Assert.Equal(storedCreatedBy, reloadedJob.CreatedBy); + Assert.Null(reloadedJob.UpdatedOnUtc); + Assert.Null(reloadedJob.UpdatedBy); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Themes/ThemeRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Themes/ThemeRepositoryTests.cs new file mode 100644 index 00000000..c7de2546 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Themes/ThemeRepositoryTests.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.DataAccess.Core.Repositories.Themes; +using Lumina.DataAccess.Core.UoW; +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.Themes; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class ThemeRepositoryTests +{ + private readonly ThemeEntityFixture _themeEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-themerepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + ThemeRepository sut = new(context); + + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + ThemeEntity storedTheme = _themeEntityFixture.Create(createdOnUtc: storedCreatedOnUtc, createdBy: storedCreatedBy); + context.Themes.Add(storedTheme); + await context.SaveChangesAsync(); + + ThemeEntity updatedTheme = _themeEntityFixture.Create( + id: storedTheme.Id, + themeId: storedTheme.ThemeId, + name: "Updated Theme", + description: storedTheme.Description, + author: storedTheme.Author, + version: storedTheme.Version, + installSource: storedTheme.InstallSource, + createdOnUtc: DateTime.UtcNow.AddYears(-10), + createdBy: Guid.NewGuid(), + includeUpdatedOnUtc: true, + updatedOnUtc: DateTime.UtcNow.AddYears(-5), + includeUpdatedBy: true, + updatedBy: Guid.NewGuid()); + + // Act + Result result = await sut.UpdateAsync(updatedTheme, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + ThemeEntity reloadedTheme = await context.Themes.AsNoTracking().FirstAsync(theme => theme.Id == storedTheme.Id); + Assert.Equal("Updated Theme", reloadedTheme.Name); + Assert.Equal(storedCreatedOnUtc, reloadedTheme.CreatedOnUtc); + Assert.Equal(storedCreatedBy, reloadedTheme.CreatedBy); + Assert.Null(reloadedTheme.UpdatedOnUtc); + Assert.Null(reloadedTheme.UpdatedBy); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserRepositoryTests.cs new file mode 100644 index 00000000..aac5943f --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -0,0 +1,104 @@ +#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.DataAccess.Core.Repositories.Users; +using Lumina.DataAccess.Core.UoW; +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.Users; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class UserRepositoryTests +{ + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-userrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + UserRepository sut = new(context); + + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + UserEntity storedUser = _userEntityFixture.Create(username: "audit-user", password: "Password123"); + storedUser.CreatedOnUtc = storedCreatedOnUtc; + storedUser.CreatedBy = storedCreatedBy; + context.Users.Add(storedUser); + await context.SaveChangesAsync(); + + UserEntity updatedUser = _userEntityFixture.Create(id: storedUser.Id, username: "audit-user", password: "NewPassword123"); + updatedUser.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + updatedUser.CreatedBy = Guid.NewGuid(); + updatedUser.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5); + updatedUser.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(updatedUser, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + UserEntity reloadedUser = await context.Users.AsNoTracking().FirstAsync(user => user.Id == storedUser.Id); + Assert.Equal("NewPassword123", reloadedUser.Password); + Assert.Equal(storedCreatedOnUtc, reloadedUser.CreatedOnUtc); + Assert.Equal(storedCreatedBy, reloadedUser.CreatedBy); + Assert.Null(reloadedUser.UpdatedOnUtc); + Assert.Null(reloadedUser.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenNothingChanged_ShouldNotDuplicateThePermissions() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-userrepo-permissions-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + UserRepository sut = new(context); + + PermissionEntity firstPermission = _permissionEntityFixture.Create(); + PermissionEntity secondPermission = _permissionEntityFixture.Create(); + UserEntity storedUser = _userEntityFixture.Create(username: $"perm-user-{Guid.NewGuid():N}", password: "Password123"); + context.Permissions.AddRange(firstPermission, secondPermission); + context.Users.Add(storedUser); + await context.SaveChangesAsync(); + storedUser.UserPermissions.Add(_userPermissionEntityFixture.Create(storedUser, firstPermission)); + storedUser.UserPermissions.Add(_userPermissionEntityFixture.Create(storedUser, secondPermission)); + await context.SaveChangesAsync(); + // Detach the seeded user, so that the update must load it through its include chain instead of returning the already populated seeded instance. + context.ChangeTracker.Clear(); + + UserEntity incoming = await context.Users.AsNoTracking().Include(candidate => candidate.UserPermissions).FirstAsync(candidate => candidate.Id == storedUser.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + UserEntity? reloadedUser = await context.Users.AsNoTracking().Include(candidate => candidate.UserPermissions).FirstOrDefaultAsync(candidate => candidate.Id == storedUser.Id); + Assert.NotNull(reloadedUser); + Assert.Equal(2, reloadedUser!.UserPermissions.Count); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs new file mode 100644 index 00000000..4ed35bfa --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.Repositories.Users; +using Lumina.DataAccess.Core.UoW; +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.Users; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsRepositoryTests +{ + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenAnEditableValueChanges_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-usersettingsrepo-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = new(new DbContextOptionsBuilder().UseSqlite(anchorConnection.ConnectionString).Options); + context.Database.EnsureCreated(); + UserSettingsRepository sut = new(context); + + UserEntity storedUser = _userEntityFixture.Create(username: "settings-user", password: "Password123"); + context.Users.Add(storedUser); + await context.SaveChangesAsync(); + + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: storedUser.Id, itemsPerPage: 10); + storedSettings.CreatedOnUtc = storedCreatedOnUtc; + storedSettings.CreatedBy = storedCreatedBy; + context.UserSettings.Add(storedSettings); + await context.SaveChangesAsync(); + + UserSettingsEntity updatedSettings = _userSettingsEntityFixture.Create(id: storedSettings.Id, userId: storedUser.Id, itemsPerPage: 25); + updatedSettings.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + updatedSettings.CreatedBy = Guid.NewGuid(); + updatedSettings.UpdatedOnUtc = DateTime.UtcNow.AddYears(-5); + updatedSettings.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await sut.UpdateAsync(updatedSettings, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + await context.SaveChangesAsync(); + context.ChangeTracker.Clear(); + UserSettingsEntity reloadedSettings = await context.UserSettings.AsNoTracking().FirstAsync(settings => settings.Id == storedSettings.Id); + Assert.Equal(25, reloadedSettings.ItemsPerPage); + Assert.Equal(storedCreatedOnUtc, reloadedSettings.CreatedOnUtc); + Assert.Equal(storedCreatedBy, reloadedSettings.CreatedBy); + Assert.Null(reloadedSettings.UpdatedOnUtc); + Assert.Null(reloadedSettings.UpdatedBy); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs index 52e5e233..b46416e8 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs @@ -47,7 +47,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(32, tableNames.Length); + Assert.Equal(46, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -80,6 +80,20 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("ScheduledJobs", tableNames); Assert.Contains("ScheduledJobExecutions", tableNames); Assert.Contains("SchedulerDisplayPreferences", tableNames); + Assert.Contains("Artists", tableNames); + Assert.Contains("Albums", tableNames); + Assert.Contains("Tracks", tableNames); + Assert.Contains("ArtistContributors", tableNames); + Assert.Contains("AlbumContributors", tableNames); + Assert.Contains("AlbumGenres", tableNames); + Assert.Contains("AlbumRatings", tableNames); + Assert.Contains("AlbumTags", 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); } [Fact] diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs index c8adc54e..0192ef7b 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/UnitOfWorkTests.cs @@ -1,7 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using System; @@ -9,6 +12,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.DataAccess.IntegrationTests.Core.UoW; @@ -20,6 +24,7 @@ namespace Lumina.DataAccess.IntegrationTests.Core.UoW; public class UnitOfWorkTests { private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); [Fact] public async Task BeginTransactionAsync_WhenCalled_ShouldBeginTransactionOnTheDatabase() @@ -177,6 +182,40 @@ public class UnitOfWorkTests } } + [Fact] + public async Task SaveChangesAsync_WhenInsertingTwoBooksWithTheSameLibraryAndPath_ShouldReturnUniqueConstraintViolationError() + { + // Arrange + (SqliteConnection anchorConnection, LuminaDbContext dbContext) = CreateSqliteContext(); + using (anchorConnection) + { + using (dbContext) + { + UnitOfWork sut = new(dbContext); + Guid libraryId = Guid.NewGuid(); + BookEntity firstBook = _bookEntityFixture.Create(); + firstBook.LibraryId = libraryId; + firstBook.Path = "/books/duplicate.epub"; + _ = await sut.BookRepository.InsertAsync(firstBook, CancellationToken.None); + Result firstSaveResult = await sut.SaveChangesAsync(CancellationToken.None); + Assert.False(firstSaveResult.IsFailure); + + // stage a second book with the same library and path directly, bypassing the application level pre-check, so that the unique index of the storage medium is the one that rejects it + BookEntity secondBook = _bookEntityFixture.Create(); + secondBook.LibraryId = libraryId; + secondBook.Path = "/books/duplicate.epub"; + dbContext.Books.Add(secondBook); + + // Act + Result result = await sut.SaveChangesAsync(CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + } + } + /// /// Creates a real SQLite in-memory context, kept alive by an anchor connection, because transactions are not supported by the in-memory provider. /// diff --git a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs index 85de2f66..cdd3a0e8 100644 --- a/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs +++ b/tests/IntegrationTests/Lumina.Infrastructure.IntegrationTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -64,6 +64,7 @@ public class BooksFileSystemDiscoveryJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockStagingResultsRepository = Substitute.For(); _mockDirectoryScanFingerprintRepository = Substitute.For(); @@ -105,7 +106,7 @@ public class BooksFileSystemDiscoveryJobTests libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], shouldSkipUnchangedDirectoriesDuringScan: false); - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From(Result.Created)); @@ -154,7 +155,7 @@ public class BooksFileSystemDiscoveryJobTests libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], shouldSkipUnchangedDirectoriesDuringScan: true); - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From(new Dictionary @@ -200,7 +201,7 @@ public class BooksFileSystemDiscoveryJobTests libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], shouldSkipUnchangedDirectoriesDuringScan: true); - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to load the directory scan fingerprints")); @@ -228,7 +229,7 @@ public class BooksFileSystemDiscoveryJobTests libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], shouldSkipUnchangedDirectoriesDuringScan: true); - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockDirectoryScanFingerprintRepository.GetMappedByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From(new Dictionary())); @@ -259,7 +260,7 @@ public class BooksFileSystemDiscoveryJobTests libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], shouldSkipUnchangedDirectoriesDuringScan: false); - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to insert the staging results")); @@ -289,7 +290,7 @@ public class BooksFileSystemDiscoveryJobTests libraryType: LibraryType.Book, contentLocations: [temporaryLibraryDirectory.Path], shouldSkipUnchangedDirectoriesDuringScan: false); - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(libraryEntity)); _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From(Result.Created)); 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 3fadeb90..043d7e42 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 @@ -67,6 +67,7 @@ public class BookReadingServiceTests : IDisposable _mockPluginManager.GetPlugins().Returns([_mockPlugin]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository); LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs deleted file mode 100644 index 28bdf8db..00000000 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs +++ /dev/null @@ -1,286 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.ValueObjects.Metadata; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters; - -/// -/// Custom JSON converter for the class. -/// -[ExcludeFromCodeCoverage] -public class BookJsonConverter : JsonConverter -{ - /// - /// Reads and converts JSON to a object. - /// - /// The JSON reader. - /// The type of the object to convert. - /// The serializer options. - /// The converted object. - public override Book Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - using (JsonDocument doc = JsonDocument.ParseValue(ref reader)) - { - JsonElement root = doc.RootElement; - - Guid id = root.GetProperty("id").GetGuid(); - Guid libraryId = root.GetProperty("libraryId").GetGuid(); - string path = root.GetProperty("path").GetString()!; - DateTime createdOnUtc = root.GetProperty("createdOnUtc").GetDateTime(); - WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata")); - BookFormat? format = null; - if (root.TryGetProperty("format", out JsonElement formatElement)) - { - if (formatElement.ValueKind == JsonValueKind.String) - { - string formatString = formatElement.GetString()!; - if (Enum.TryParse(formatString, out BookFormat parsedFormat)) - format = parsedFormat; - } - } - string? edition = root.GetProperty("edition").GetString(); - int volumeNumber = root.GetProperty("volumeNumber").GetInt32(); - BookSeries series = DeserializeBookSeries(root.GetProperty("series")); - string? asin = root.GetProperty("asin").GetString(); - string? goodreadsId = root.GetProperty("goodreadsId").GetString(); - string? lccn = root.GetProperty("lccn").GetString(); - string? oclcNumber = root.GetProperty("oclcNumber").GetString(); - string? openLibraryId = root.GetProperty("openLibraryId").GetString(); - string? libraryThingId = root.GetProperty("libraryThingId").GetString(); - string? googleBooksId = root.GetProperty("googleBooksId").GetString(); - string? barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString(); - string? appleBooksId = root.GetProperty("appleBooksId").GetString(); - List isbns = DeserializeIsbns(root.GetProperty("isbNs")); - List contributorIds = DeserializeContributorIds(root.GetProperty("contributors")); - List ratings = DeserializeRatings(root.GetProperty("ratings")); - - Result createBookResult = Book.Create( - BookId.Create(id), - LibraryId.Create(libraryId), - path, - metadata, - Optional.FromNullable(format), - Optional.FromNullable(edition), - volumeNumber, - Optional.FromNullable(series), - Optional.FromNullable(asin), - Optional.FromNullable(goodreadsId), - Optional.FromNullable(lccn), - Optional.FromNullable(oclcNumber), - Optional.FromNullable(openLibraryId), - Optional.FromNullable(libraryThingId), - Optional.FromNullable(googleBooksId), - Optional.FromNullable(barnesAndNobleId), - Optional.FromNullable(appleBooksId), - createdOnUtc, - default, - isbns, - contributorIds, - ratings: ratings - ); - if (createBookResult.IsFailure) - throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}"); - return createBookResult.Value; - } - } - - /// - /// Writes a object to JSON. This method is not implemented. - /// - /// The JSON writer. - /// The object to write. - /// The serializer options. - public override void Write(Utf8JsonWriter writer, Book value, JsonSerializerOptions options) - { - throw new NotImplementedException("Serialization is not implemented for Book class."); - } - - /// - /// Deserializes the metadata from JSON. - /// - /// The JSON element containing the metadata. - /// The deserialized . - private static WrittenContentMetadata DeserializeMetadata(JsonElement element) - { - string? title = element.GetProperty("title").GetString(); - string? originalTitle = element.GetProperty("originalTitle").GetString(); - string? description = element.GetProperty("description").GetString(); - ReleaseInfo releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo")); - List genres = DeserializeGenres(element.GetProperty("genres")); - List tags = DeserializeTags(element.GetProperty("tags")); - LanguageInfo? language = DeserializeLanguageInfo(element.GetProperty("language")); - LanguageInfo? originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage")); - string? publisher = element.GetProperty("publisher").GetString(); - int? pageCount = null; - if (element.TryGetProperty("pageCount", out JsonElement pageCountElement)) - if (pageCountElement.ValueKind != JsonValueKind.Null) - pageCount = pageCountElement.GetInt32(); - Result metadataResult = WrittenContentMetadata.Create( - title!, - Optional.FromNullable(originalTitle), - Optional.FromNullable(description), - releaseInfo, - genres, - tags, - Optional.FromNullable(language), - Optional.FromNullable(originalLanguage), - Optional.FromNullable(publisher), - Optional.FromNullable(pageCount) - ); - - if (metadataResult.IsFailure) - throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}"); - return metadataResult.Value; - } - - /// - /// Deserializes the release info from JSON. - /// - /// The JSON element containing the release info. - /// The deserialized . - private static ReleaseInfo DeserializeReleaseInfo(JsonElement element) - { - DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) && ordElement.ValueKind != JsonValueKind.Null ? - DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null; - int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number - ? oryElement.GetInt32() : (int?)null; - DateOnly? reReleaseDate = element.TryGetProperty("reReleaseDate", out JsonElement rrdElement) && rrdElement.ValueKind == JsonValueKind.String ? - DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null; - int? reReleaseYear = element.TryGetProperty("reReleaseYear", out JsonElement rryElement) && rryElement.ValueKind == JsonValueKind.Number - ? rryElement.GetInt32() : (int?)null; - string? releaseCountry = element.TryGetProperty("releaseCountry", out JsonElement rcElement) ? - rcElement.GetString() : null; - string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ? - rvElement.GetString() : null; - - Optional releaseCountryValue = Optional.None(); - if (releaseCountry is not null && Enum.TryParse(releaseCountry, ignoreCase: true, out ReleaseCountry parsedReleaseCountry)) - releaseCountryValue = parsedReleaseCountry; - Result releaseInfoResult = ReleaseInfo.Create( - Optional.FromNullable(originalReleaseDate), - Optional.FromNullable(originalReleaseYear), - Optional.FromNullable(reReleaseDate), - Optional.FromNullable(reReleaseYear), - releaseCountryValue, - Optional.FromNullable(releaseVersion) - ); - - if (releaseInfoResult.IsFailure) - throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}"); - return releaseInfoResult.Value; - } - - /// - /// Deserializes the genres from JSON. - /// - /// The JSON element containing the genres. - /// The deserialized list of . - private static List DeserializeGenres(JsonElement element) - { - return [.. element.EnumerateArray().Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)]; - } - - /// - /// Deserializes the tags from JSON. - /// - /// The JSON element containing the tags. - /// The deserialized list of . - private static List DeserializeTags(JsonElement element) - { - return [.. element.EnumerateArray().Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)]; - } - - /// - /// Deserializes the language info from JSON. - /// - /// The JSON element containing the language info. - /// The deserialized . - private static LanguageInfo? DeserializeLanguageInfo(JsonElement element) - { - if (element.ValueKind != JsonValueKind.Null) - { - string? languageCode = element.GetProperty("languageCode").GetString(); - string? languageName = element.GetProperty("languageName").GetString(); - string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null; - - Result languageInfoResult = LanguageInfo.Create( - languageCode!, - languageName!, - Optional.FromNullable(nativeName) - ); - - if (languageInfoResult.IsFailure) - throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}"); - return languageInfoResult.Value; - } - else - return null; - } - - /// - /// Deserializes the book series from JSON. - /// - /// The JSON element containing the book series. - /// The deserialized . - private static BookSeries DeserializeBookSeries(JsonElement element) - { - // TODO: implement when book series are implemented - return null!; - } - - /// - /// Deserializes the ISBNs from JSON. - /// - /// The JSON element containing the ISBNs. - /// The deserialized list of . - private static List DeserializeIsbns(JsonElement element) - { - return [.. element.EnumerateArray() - .Select(i => Isbn.Create(i.GetProperty("value").GetString()!, - Enum.Parse(i.GetProperty("format").GetString()!)).Value)]; - } - - /// - /// Deserializes the contributor IDs from JSON. - /// - /// The JSON element containing the contributor IDs. - /// The deserialized list of . - private static List DeserializeContributorIds(JsonElement element) - { - // TODO: implement when contributors are implemented - return []; - } - - /// - /// Deserializes the ratings from JSON. - /// - /// The JSON element containing the ratings. - /// The deserialized list of . - private static List DeserializeRatings(JsonElement element) - { - return [.. element.EnumerateArray() - .Select(r => BookRating.Create( - r.GetProperty("value").GetInt32(), - r.GetProperty("maxValue").GetInt32(), - Optional.FromNullable(Enum.Parse(r.GetProperty("source").GetString()!)), - Optional.FromNullable( - r.TryGetProperty("voteCount", out JsonElement voteCountElement) && voteCountElement.ValueKind != JsonValueKind.Null - ? voteCountElement.GetInt32() - : (int?)null) - ).Value)]; - } -} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index e37ab2d7..ea77f98e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -29,7 +29,6 @@ public class GetDirectoriesEndpointTests : IClassFixture /// The Id of the user that owns the library. - /// The Id of the seeded book. - private async Task SeedBookAsync(Guid userId) + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -120,7 +158,7 @@ public class GetReadingManifestEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index a2db9592..a47ca9e1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Net.Http; +using System.Text.Json; using System.Threading.Tasks; #endregion @@ -52,7 +53,7 @@ public class GetReadingResourceEndpointTests : IClassFixture /// Seeds a library owned by and an EPUB book belonging to it. /// /// The Id of the user that owns the library. - /// The Id of the seeded book. - private async Task SeedBookAsync(Guid userId) + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -120,7 +158,7 @@ public class GetReadingResourceEndpointTests : IClassFixture diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index 209f6ddd..50094847 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -13,6 +13,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Net.Http; +using System.Text.Json; using System.Threading.Tasks; #endregion @@ -52,7 +53,7 @@ public class GetReadingSectionEndpointTests : IClassFixture /// Seeds a library owned by and an EPUB book belonging to it. /// /// The Id of the user that owns the library. - /// The Id of the seeded book. - private async Task SeedBookAsync(Guid userId) + /// The Ids of the seeded library and book. + private async Task<(Guid libraryId, Guid bookId)> SeedBookAsync(Guid userId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -120,7 +158,7 @@ public class GetReadingSectionEndpointTests : IClassFixture 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 a7ae66b2..41887801 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 @@ -1,17 +1,25 @@ #region ========================================================================= USING ===================================================================================== +using Bogus; 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.UsersManagement; +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.UsersManagement; +using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; @@ -27,6 +35,7 @@ using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading; using System.Threading.Tasks; #endregion @@ -46,9 +55,17 @@ public class UpdateBookEndpointTests : IClassFixture @@ -75,10 +92,10 @@ public class UpdateBookEndpointTests : IClassFixture duplicatedContributors = + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + Guid contributorId = Guid.NewGuid(); + List duplicatedContributors = [ - new MediaContributorDto( - new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"), - new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author)), - new MediaContributorDto( - new MediaContributorNameDto("Duplicated Author", "Duplicated Author Legal"), - new MediaContributorRoleDto("illustrator", MediaContributorRoleCategory.Illustrator)) + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator) ]; - UpdateBookRequest request = _requestBookFixture.Create(id: bookId, contributors: duplicatedContributors, isbns: [], ratings: [], includeOptionalProperties: false); + await SeedContributorsAsync(duplicatedContributors); + UpdateBookRequest request = _requestBookFixture.Create(contributors: duplicatedContributors, isbns: [], 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 - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{bookId}", request); + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - MediaContributorEntity contributor = dbContext.MediaContributors.Single(mediaContributor => mediaContributor.DisplayName == "Duplicated Author"); - List links = dbContext.Books - .Include(book => book.BookContributors) + List links = [.. dbContext.Books + .Include(book => book.Contributors) .Single(book => book.Id == bookId) - .BookContributors - .ToList(); + .Contributors]; Assert.Equal(2, links.Count); - Assert.All(links, link => Assert.Equal(contributor.Id, link.MediaContributorId)); - Assert.Contains(links, link => link.RoleName == "author"); - Assert.Contains(links, link => link.RoleName == "illustrator"); + Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId)); + Assert.Contains(links, link => link.Role == MediaContributorRole.Author); + Assert.Contains(links, link => link.Role == MediaContributorRole.Illustrator); } [Fact] - public async Task UpdateBook_WhenRouteBookDoesNotExistButBodyIdExists_ShouldNotUpdateTheBodyBook() + public async Task UpdateBook_WhenRouteBookDoesNotExist_ShouldNotUpdateAnyBook() { // Arrange Guid userId = GetCurrentUserId(); (Guid libraryId, Guid bodyBookId) = await SeedLibraryAndBookAsync(userId, "Body Book Title"); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _requestBookFixture.Create(id: bodyBookId, metadata: _writtenContentMetadataDtoFixture.Create(title: "Should Not Apply")); + UpdateBookRequest request = _requestBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: "Should Not Apply")); // Act - HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/books/{routeId}", request); + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{routeId}", request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -157,10 +170,11 @@ public class UpdateBookEndpointTests : IClassFixture + await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token) + ); + Assert.Null(exception); + } + + [Fact] + public async Task UpdateBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + UpdateBookRequest request = _requestBookFixture.Create(); + using CancellationTokenSource cts = new(); + + // Act & Assert + Exception? exception = await Record.ExceptionAsync(async () => + { + cts.Cancel(); + await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request, cts.Token); + }); + Assert.IsType(exception); + } + + /// + /// Updates the book described by the provided request, seeding the media library, the book and the referenced media contributors. + /// + /// The request to send. + /// The HTTP response of the PUT request. + private async Task PutBookAsync(UpdateBookRequest request) + { + Guid userId = GetCurrentUserId(); + (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, "Original Title"); + await SeedContributorsAsync(request.Contributors); + return await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert. + /// The validation error codes expected in the response. + private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"])); + } + /// /// Seeds a library owned by and a book belonging to it. /// @@ -261,6 +1882,26 @@ public class UpdateBookEndpointTests : IClassFixture + /// Seeds the media contributors referenced by the provided book contributors, so that the handler finds them already existing. + /// + /// The contributors of the book request. + private async Task SeedContributorsAsync(List? contributors) + { + if (contributors is null || contributors.Count == 0) + return; + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + foreach (Guid contributorId in contributors.Select(contributor => contributor.ContributorId).Distinct()) + { + if (contributorId == Guid.Empty || await dbContext.MediaContributors.AnyAsync(contributor => contributor.Id == contributorId)) + continue; + dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString())); + } + await dbContext.SaveChangesAsync(); + } + /// /// Seeds a user distinct from the authenticated test user and returns its Id. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs index 793b9e09..b4a1f722 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; 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.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -63,19 +64,19 @@ public class UpdateBookCoverEndpointTests : IClassFixture(content)!; + string storedPath = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath; Assert.False(string.IsNullOrWhiteSpace(storedPath)); Assert.Contains("cover.png", storedPath, StringComparison.OrdinalIgnoreCase); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); BookArtworkEntity coverArtwork = dbContext.Books - .SelectMany(book => book.BookArtwork) + .SelectMany(book => book.Artwork) .Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover); Assert.Equal(storedPath, coverArtwork.FileName); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); @@ -86,21 +87,21 @@ public class UpdateBookCoverEndpointTests : IClassFixture(content)!; + string storedPath = JsonSerializer.Deserialize(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!.CoverPath; Assert.False(string.IsNullOrWhiteSpace(storedPath)); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); BookArtworkEntity coverArtwork = dbContext.Books - .SelectMany(book => book.BookArtwork) + .SelectMany(book => book.Artwork) .Single(artwork => artwork.BookId == bookId && artwork.ArtworkType == ArtworkType.Cover); Assert.Equal(storedPath, coverArtwork.FileName); } @@ -109,7 +110,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture /// Creates a multipart form carrying a minimal PNG-like payload. /// @@ -181,6 +267,17 @@ public class UpdateBookCoverEndpointTests : IClassFixture + /// Creates a multipart form carrying the provided payload as an uploaded file. + /// + /// The bytes of the uploaded file. + /// The name of the uploaded file. + /// A configured instance. + private static MultipartFormDataContent CreateCoverForm(byte[] payload, string fileName) + { MultipartFormDataContent form = []; ByteArrayContent fileContent = new(payload); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); @@ -203,7 +300,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); 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 664d26dc..102b2753 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 @@ -156,7 +156,7 @@ public class InstallPluginEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); @@ -182,7 +182,7 @@ public class ChangePasswordEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); 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 f0f554c4..4540b00a 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 @@ -184,7 +184,7 @@ public class RecoverPasswordEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); @@ -219,7 +219,7 @@ public class RecoverPasswordEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 58917bf5..9802f411 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -156,7 +156,7 @@ public class RegisterEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); @@ -177,7 +177,7 @@ public class RegisterEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs index 543c9b9f..fff048ee 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -40,10 +40,10 @@ public class GetDirectoriesEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); string path = @"C:\Users\test"; DirectoryDto[] expectedDirectories = [_directoryDtoFixture.Create(path: path, name: "test")]; - string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedDirectories); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=true"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs index bd562e06..4af4fb92 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -40,10 +40,10 @@ public class GetFilesEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); string path = @"C:\Users\test"; FileDto[] expectedFiles = [_fileDtoFixture.Create(path: path, name: "book.pdf")]; - string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedFiles); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=true"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs index 1ec83afc..3619024d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -40,10 +40,10 @@ public class GetTreeFilesEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); string path = @"C:\Users\test"; FileSystemTreeNodeDto[] expectedNodes = [_fileSystemTreeNodeDtoFixture.Create(path: path, name: "test")]; - string expectedEndpoint = $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + string expectedEndpoint = $"files/get-tree-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedNodes); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-tree-files?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=true"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs index 3e95d5b2..0a1c86af 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -38,10 +38,10 @@ public class CheckPathExistsEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); string path = @"C:\Users\test"; - string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=True"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create(exists: true)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(path)}&shouldIncludeHiddenElements=true"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs index 30c7fa4e..e86bfe77 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -38,11 +38,11 @@ public class EditBookViewEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); expectedBook.Metadata!.Title = "A book"; - _apiFactory.ApiClientStub.RegisterGetResponse($"books/{expectedBook.Id}", expectedBook); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{expectedBook.LibraryId}/books/{expectedBook.Id}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); // Act - HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}"); + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{expectedBook.Id}?libraryId={expectedBook.LibraryId}"); string content = await response.Content.ReadAsStringAsync(); // Assert diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs index 822e2952..57826b29 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs @@ -38,11 +38,12 @@ public class GetBookDetailsEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); - _apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}", expectedBook); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-book?libraryId={libraryId}"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act @@ -55,7 +56,7 @@ public class GetBookDetailsEndpointTests : IClassFixture using JsonDocument json = JsonDocument.Parse(content); Assert.True(json.RootElement.GetProperty("success").GetBoolean()); Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid()); - Assert.Contains($"books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + Assert.Contains($"libraries/{libraryId}/books/{bookId}", _apiFactory.ApiClientStub.GetEndpointsCalled); } [Fact] @@ -66,10 +67,10 @@ public class GetBookDetailsEndpointTests : IClassFixture HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); // Act - HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book"); + HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}/api-get-book?libraryId={Guid.NewGuid()}"); // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase)); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs index 13b87003..27ff397e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -42,7 +42,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture Guid libraryId = Guid.NewGuid(); string searchTerm = "Harry"; PaginatedBookLiteDto expectedResponse = _paginatedBookLiteDtoFixture.Create(data: [_bookLiteDtoFixture.Create(title: "Harry Potter")]); - string expectedEndpoint = $"books/lite?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True"; + string expectedEndpoint = $"libraries/{libraryId}/books/lite?currentPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=true"); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 1501b6c7..b7bb79e3 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -38,11 +38,12 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); ReadingManifestDto manifest = _readingManifestDtoFixture.Create(title: "Test Book"); - _apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/manifest", manifest); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/manifest", manifest); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act @@ -65,12 +66,13 @@ public class GetReadingManifestEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterGetException($"books/{bookId}/reading/manifest", new ApiException( + _apiFactory.ApiClientStub.RegisterGetException($"libraries/{libraryId}/books/{bookId}/reading/manifest", new ApiException( _problemDetailsDtoFixture.Create(detail: "NoReaderAvailable"), HttpStatusCode.NotFound)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-manifest?libraryId={libraryId}"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index 5e3bbf4d..48c697eb 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -38,12 +38,13 @@ public class GetReadingSectionEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); string locationRef = "chapter-1"; ReadingSectionDto section = _readingSectionDtoFixture.Create(locationRef: locationRef, contentHtml: "

Content

"); - _apiFactory.ApiClientStub.RegisterGetResponse($"books/{bookId}/reading/sections/{locationRef}", section); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{bookId}/reading/sections/{locationRef}", section); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-get-reading-section?locationRef={locationRef}&libraryId={libraryId}"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index ff9ab793..24706b76 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -43,9 +43,10 @@ public class SaveBookEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + Guid libraryId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(bookId, request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -60,7 +61,7 @@ public class SaveBookEndpointTests : IClassFixture using JsonDocument json = JsonDocument.Parse(content); Assert.True(json.RootElement.GetProperty("success").GetBoolean()); Assert.Equal(bookId, json.RootElement.GetProperty("data").GetProperty("id").GetGuid()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == bookId.ToString()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == bookId.ToString()); } [Fact] @@ -70,9 +71,10 @@ public class SaveBookEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); Guid routeId = Guid.NewGuid(); Guid bodyId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId); + Guid libraryId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: routeId); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}", expectedBook); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(routeId, request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -84,8 +86,8 @@ public class SaveBookEndpointTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == routeId.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == routeId.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}"); } [Fact] @@ -103,7 +105,7 @@ public class SaveBookEndpointTests : IClassFixture // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}"); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{request.LibraryId}/books/{bookId}"); } [Fact] diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs index b6dd0fce..f485980a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -1,5 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; +using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; using System; @@ -21,6 +26,8 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Writte public class UpdateBookCoverEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -36,11 +43,12 @@ public class UpdateBookCoverEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); string expectedPath = "/media/books/cover.png"; - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}/cover", expectedPath); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}/cover", _updateBookCoverDtoFixture.Create(coverPath: expectedPath)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png"); uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); // Act @@ -53,7 +61,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture using JsonDocument json = JsonDocument.Parse(content); Assert.True(json.RootElement.GetProperty("success").GetBoolean()); Assert.Equal(expectedPath, json.RootElement.GetProperty("data").GetString()); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover" && putRequest.Data as string == "cover.png"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data as string == "cover.png"); } [Fact] @@ -61,11 +69,12 @@ public class UpdateBookCoverEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); Guid formId = Guid.NewGuid(); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{routeId}/cover", "/media/books/cover.png"); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{routeId}/cover", _updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.png")); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, "cover.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(routeId, libraryId, "cover.png"); uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); MultipartFormDataContent form = (MultipartFormDataContent)uploadRequest.Content!; form.Add(new StringContent(formId.ToString()), "id"); @@ -77,8 +86,8 @@ public class UpdateBookCoverEndpointTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{routeId}/cover"); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{formId}/cover"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{routeId}/cover"); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{formId}/cover"); } [Fact] @@ -86,28 +95,32 @@ public class UpdateBookCoverEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, "cover.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(bookId, libraryId, "cover.png"); // Act HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); // Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover"); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover"); } [Fact] - public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldReturnBadRequest() + public async Task UpdateBookCover_WhenCalledWithoutUploadedFile_ShouldForwardRequestAndReturnFailure() { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); + ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "BookCoverCannotBeNull"); + _apiFactory.ApiClientStub.RegisterPutException($"libraries/{libraryId}/books/{bookId}/cover", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, $"libraries/{libraryId}/books/{bookId}/cover")); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); MultipartFormDataContent noFileForm = []; noFileForm.Add(new StringContent("unrelated-field")); - HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover") + HttpRequestMessage uploadRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}") { Content = noFileForm }; @@ -116,10 +129,14 @@ public class UpdateBookCoverEndpointTests : IClassFixture // Act HttpResponseMessage response = await webClient.Client.SendAsync(uploadRequest); + string content = await response.Content.ReadAsStringAsync(); // Assert - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}/cover"); + // The web does not short-circuit the missing file; it forwards the request, and the API reports the missing cover + // with the same BookCoverCannotBeNull validation error any other client receives. + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}/cover" && putRequest.Data == null); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); } [Fact] @@ -128,7 +145,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), "cover.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid(), Guid.NewGuid(), "cover.png"); // Act HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest); @@ -142,15 +159,16 @@ public class UpdateBookCoverEndpointTests : IClassFixture /// Builds the multipart PUT request that uploads a cover to the book identified by . /// /// The route Id of the book whose cover is uploaded. + /// The Id of the media library the book belongs to. /// The name of the uploaded file. /// The configured upload request. - private static HttpRequestMessage CreateUploadRequest(Guid bookId, string fileName) + private static HttpRequestMessage CreateUploadRequest(Guid bookId, Guid libraryId, string fileName) { MultipartFormDataContent form = []; ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(fileContent, "cover", fileName); - return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover") + return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-update-cover?libraryId={libraryId}") { Content = form }; diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs index 8de229a1..659b8547 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -220,6 +220,24 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable } } + /// + /// Removes a test user and its owned libraries from the database. + /// + /// The username of the test user to remove. + public void RemoveTestUser(string username) + { + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.Include(candidate => candidate.Libraries).FirstOrDefault(candidate => candidate.Username == username); + if (user is not null) + { + dbContext.Libraries.RemoveRange(user.Libraries); + dbContext.Users.Remove(user); + dbContext.SaveChanges(); + } + } + /// /// Removes a test admin user, its role, and its user-role link from the database. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs index 2e999266..bb93e13b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs @@ -120,6 +120,53 @@ public class UpdateRoleEndpointTests : IClassFixture, IAsyncDi Assert.Equal(maliciousRoleName, updatedRole!.RoleName); } + [Fact] + public async Task UpdateRole_WhenAuthenticatedNonAdmin_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededPermissionId = Guid.NewGuid(); + _seededRoleId = Guid.NewGuid(); + RoleEntity seededRole = _roleEntityFixture.Create(id: _seededRoleId, roleName: "ExistingRole"); + using (IServiceScope seedScope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService(); + seedDbContext.Permissions.Add(_permissionEntityFixture.Create(id: _seededPermissionId, permissionName: AuthorizationPermission.CanDeleteUsers)); + seedDbContext.Roles.Add(seededRole); + await seedDbContext.SaveChangesAsync(); + } + UpdateRoleRequest requestBody = _updateRoleRequestFixture.Create( + roleId: seededRole.Id, + roleName: "Hijacked", + permissions: [_seededPermissionId] + ); + StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await client.PutAsync("/api/v1/auth/roles", content); + string responseContent = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(responseContent, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", responseContent, StringComparison.OrdinalIgnoreCase); + + // The role is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + RoleEntity? storedRole = await dbContext.Roles.FirstOrDefaultAsync(role => role.Id == seededRole.Id); + Assert.NotNull(storedRole); + Assert.Equal("ExistingRole", storedRole!.RoleName); + + await _apiFactory.RemoveTestUserAsync(username); + } + /// /// Disposes API factory resources. /// 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 new file mode 100644 index 00000000..c3d08c2c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.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.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddAlbumEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddAlbumEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task AddAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request); + + // 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task AddAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task AddAlbum_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task AddAlbum_WithSQLInjectionInArtistRouteId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("ArtistIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + (Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(userId); + AddAlbumRequest request = _addAlbumRequestFixture.Create( + metadata: _albumMetadataDtoFixture.Create(title: maliciousTitle), + contributors: [], + ratings: [], + tracks: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request); + + // Assert + // The malicious title passes validation, reaches the parameterized insert, and is persisted verbatim: if it were + // concatenated into raw SQL, the insert would fail and the album would not be created. + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(2, await dbContext.Albums.CountAsync(album => album.LibraryId == libraryId)); + + } + + [Fact] + public async Task AddAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid libraryId, Guid artistId) = await SeedLibraryArtistAndAlbumAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + AddAlbumRequest request = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by , together with an artist that owns one album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs new file mode 100644 index 00000000..c22f6d2d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs @@ -0,0 +1,262 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteAlbumEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteAlbumEndpointTests(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 DeleteAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistWithTwoAlbumsAsync(otherUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task DeleteAlbum_WhenAlbumBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _, _) = await SeedLibraryArtistWithTwoAlbumsAsync(actingUserId); + + // The album lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId, Guid victimAlbumId) = await SeedLibraryArtistWithTwoAlbumsAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's album is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId)); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist that owns two albums. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and the first album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistWithTwoAlbumsAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid otherAlbumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + AlbumEntity otherAlbum = _albumEntityFixture.Create(id: otherAlbumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album, otherAlbum], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs new file mode 100644 index 00000000..29503bcf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs @@ -0,0 +1,219 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetAlbumEndpointTests(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 GetAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbum_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbum_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbum_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetAlbum_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist and one of its albums. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs new file mode 100644 index 00000000..1506e1fd --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs @@ -0,0 +1,222 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetAlbumTracksEndpointTests(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 GetAlbumTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbumTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbumTracks_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbumTracks_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetAlbumTracks_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist, one of its albums and one of its tracks. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs new file mode 100644 index 00000000..0aaa8260 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs @@ -0,0 +1,222 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetAlbumTracksLiteEndpointTests(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 GetAlbumTracksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbumTracksLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbumTracksLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetAlbumTracksLite_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetAlbumTracksLite_WhenAlbumBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId, _) = await SeedArtistAlbumWithTrackAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist, one of its albums and one of its tracks. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedArtistAlbumWithTrackAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", title: "We Are the Champions", includeMetadata: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", tracks: [track], includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs new file mode 100644 index 00000000..15190c19 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs @@ -0,0 +1,294 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.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.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateAlbumEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateAlbum_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(401, 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task UpdateAlbum_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbum_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (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: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request); + + // Assert + // The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were + // concatenated into raw SQL, the update would fail and the album would not be updated. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == albumId); + Assert.NotNull(storedAlbum); + Assert.Equal(maliciousTitle, storedAlbum!.Title); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbum_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbum_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Albums; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateAlbum_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdateAlbum_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId); + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + _seededUsernames.Add(requesterUsername); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(contributors: [], ratings: []); + + // Act + HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateAlbum_WhenResourceBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _, _) = await SeedLibraryArtistAndAlbumAsync(actingUserId); + + // The resource lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (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: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's album is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + AlbumEntity? storedAlbum = await dbContext.Albums.FirstOrDefaultAsync(album => album.Id == victimAlbumId); + Assert.NotNull(storedAlbum); + Assert.Equal("News of the World", storedAlbum.Title); + } + + /// + /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload. + /// + /// The HTTP response to assert. + /// The injected payload that must never be echoed back. + /// The validation error code expected in the response. + private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal); + } + + /// + /// Seeds a music library owned by , together with an artist and one of its albums. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "News of the World", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} 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 new file mode 100644 index 00000000..42a97d3b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs @@ -0,0 +1,208 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +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; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task AddArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); + + // 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task AddArtist_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task AddArtist_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + AddArtistRequest request = _addArtistRequestFixture.Create(name: "Queen", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists", request); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddArtist_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousName) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid libraryId = await SeedLibraryAsync(userId); + AddAlbumRequest album = _addAlbumRequestFixture.Create(contributors: [], ratings: [], tracks: []); + AddArtistRequest request = _addArtistRequestFixture.Create(name: maliciousName, contributors: [], albums: [album]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); + + // Assert + // The malicious name passes validation, reaches the parameterized insert, and is persisted verbatim: if it were + // concatenated into raw SQL, the insert would fail and the artist would not be created. + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId)); + + } + + [Fact] + public async Task AddArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = await SeedLibraryAsync(ownerId); + + (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]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs new file mode 100644 index 00000000..97c26687 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs @@ -0,0 +1,233 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteArtistEndpointTests(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 DeleteArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task DeleteArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task DeleteArtist_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _) = await SeedLibraryAndArtistAsync(actingUserId); + + // The artist lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId) = await SeedLibraryAndArtistAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's artist is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId)); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist of that library. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs new file mode 100644 index 00000000..5ef58622 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistEndpointTests(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 GetArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtist_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtist_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetArtist_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist of that library. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs new file mode 100644 index 00000000..49dcd05c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistAlbumsEndpointTests(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 GetArtistAlbums_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbums_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbums_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetArtistAlbums_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist of that library. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs new file mode 100644 index 00000000..1c681ab4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs @@ -0,0 +1,192 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistAlbumsLiteEndpointTests(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 GetArtistAlbumsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/lite"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbumsLite_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistAlbumsLite_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetArtistAlbumsLite_WhenArtistBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId) = await SeedLibraryAndArtistAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a music library owned by , together with an artist of that library. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library and artist. + private async Task<(Guid libraryId, Guid artistId)> SeedLibraryAndArtistAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs new file mode 100644 index 00000000..fa05b321 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs @@ -0,0 +1,194 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistsEndpointTests(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 GetArtists_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetArtists_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedArtistAsync(libraryId, "Queen"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal); + + // the injected statement must never be executed: the Artists table and the seeded rows must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId)); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtists_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task GetArtists_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = await SeedLibraryAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds an artist belonging to the media library identified by . + /// + /// The Id of the media library the artist belongs to. + /// The name of the artist. + /// A task representing the asynchronous operation. + private async Task SeedArtistAsync(Guid libraryId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs new file mode 100644 index 00000000..ec5ae14e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs @@ -0,0 +1,193 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetArtistsLiteEndpointTests(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 GetArtistsLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/lite"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetArtistsLite_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedArtistAsync(libraryId, "Queen"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal); + + // the injected statement must never be executed: the Artists table and the seeded rows must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Artists.CountAsync(artist => artist.LibraryId == libraryId)); + + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetArtistsLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/lite"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task GetArtistsLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = await SeedLibraryAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/lite"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds an artist belonging to the media library identified by . + /// + /// The Id of the media library the artist belongs to. + /// The name of the artist. + /// A task representing the asynchronous operation. + private async Task SeedArtistAsync(Guid libraryId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Artists.Add(_artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs new file mode 100644 index 00000000..909cc08b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs @@ -0,0 +1,311 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new(); + private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateArtistEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateArtist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(401, 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task UpdateArtist_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtist_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousName) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid libraryId = Guid.NewGuid(); + (Guid artistId, Guid albumId) = await SeedArtistAsync(libraryId, userId); + UpdateArtistAlbumRequest album = _updateArtistAlbumRequestFixture.Create( + albumId: albumId, + metadata: _albumMetadataDtoFixture.Create(title: "Updated Album"), + contributors: [], + ratings: [], + tracks: []); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: maliciousName, contributors: [], albums: [album]); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + // The malicious name passes validation, reaches the parameterized update, and is persisted verbatim: if it were + // concatenated into raw SQL, the update would fail and the artist would not be updated. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == artistId); + Assert.NotNull(storedArtist); + Assert.Equal(maliciousName, storedArtist!.Name); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtist_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Artists; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateArtist_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdateArtist_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid libraryId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Hash", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateArtist_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = Guid.NewGuid(); + (Guid artistId, _) = await SeedArtistAsync(libraryId, ownerId); + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + _seededUsernames.Add(requesterUsername); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateArtist_WhenArtistBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + Guid ownLibraryId = Guid.NewGuid(); + await SeedArtistAsync(ownLibraryId, actingUserId); + + // The artist lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + Guid victimLibraryId = Guid.NewGuid(); + (Guid victimArtistId, _) = await SeedArtistAsync(victimLibraryId, victimUserId); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(name: "Hijacked", contributors: [], albums: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's artist is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + ArtistEntity? storedArtist = await dbContext.Artists.FirstOrDefaultAsync(artist => artist.Id == victimArtistId); + Assert.NotNull(storedArtist); + Assert.Equal("Queen", storedArtist.Name); + } + + /// + /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload. + /// + /// The HTTP response to assert. + /// The injected payload that must never be echoed back. + /// The validation error code expected in the response. + private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal); + } + + /// + /// Seeds a music library owned by , together with an artist that owns one album. + /// + /// The Id of the media library to seed. + /// The Id of the user that owns the media library. + /// The Ids of the seeded artist and of its album. + private async Task<(Guid artistId, Guid albumId)> SeedArtistAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false, includeBarcode: false, includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", albums: [album], includeContributors: false)); + await dbContext.SaveChangesAsync(); + return (artistId, albumId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} 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 new file mode 100644 index 00000000..614bd079 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs @@ -0,0 +1,279 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.AddTrack; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddTrackEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly List _seededUsernames = []; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly string _libraryContentLocation = Path.GetTempPath(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddTrackEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task AddTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request); + + // 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task AddTrack_WhenUnauthorized_ShouldNotLeakSensitiveData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task AddTrack_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(requesterUsername); + AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + } + + [Fact] + public async Task AddTrack_WhenArtistBelongsToAnotherLibrary_ShouldNotDiscloseCrossLibraryData() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid ownerLibraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(ownerId); + + (Guid attackerId, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(attackerUsername); + Guid attackerLibraryId = Guid.NewGuid(); + using (IServiceScope seedScope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService(); + seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: attackerLibraryId, userId: attackerId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [_libraryContentLocation])); + await seedDbContext.SaveChangesAsync(); + } + AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{attackerLibraryId}/artists/{artistId}/albums/{albumId}/tracks", request); + + // Assert + // The artist exists in another library, but the mismatch is reported as not found, without disclosing that it exists elsewhere. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("ArtistNotFound", content, StringComparison.Ordinal); + Assert.DoesNotContain(ownerLibraryId.ToString(), content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddTrack_WithSQLInjectionInPath_ShouldNotCorruptOrDeleteData(string maliciousPath) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + (Guid libraryId, Guid artistId, Guid albumId) = await SeedLibraryArtistAndAlbumAsync(userId); + string injectedPath = Path.Combine(_libraryContentLocation, $"{maliciousPath}.flac"); + AddTrackRequest request = _addTrackRequestFixture.Create(path: injectedPath, contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request); + + // Assert + // The malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted + // verbatim: if it were concatenated into raw SQL, the insert would fail and the track would not be created. + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId)); + TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId); + Assert.Equal(injectedPath, storedTrack.Path); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddTrack_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle) + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + (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), + contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", request); + + // Assert + // The malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted + // verbatim: if it were concatenated into raw SQL, the insert would fail and the track would not be created. + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + TrackEntity storedTrack = await dbContext.Tracks.SingleAsync(track => track.LibraryId == libraryId); + Assert.Equal(maliciousTitle, storedTrack.Title); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddTrack_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + AddTrackRequest request = _addTrackRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks", request); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a music library owned by , along with one artist and one album of that library. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist and album. + private async Task<(Guid libraryId, Guid artistId, Guid albumId)> SeedLibraryArtistAndAlbumAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_libraryContentLocation])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs new file mode 100644 index 00000000..065a77f4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs @@ -0,0 +1,356 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteTrackEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteTrackEndpointTests(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 DeleteTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"); + + // Assert + // The route value is kept as a raw string, so the unparseable Id reaches the command validator, which reports a clean + // validation error instead of failing the request binding. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task DeleteTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}"); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("..%2F..%2Fevil")] // encoded slash traversal + [InlineData("%2e%2e%2f%2e%2e%2fevil")] // encoded dot-slash traversal + [InlineData("..%5Cevil")] // encoded backslash traversal + [InlineData("..%2F")] // encoded trailing slash traversal + public async Task DeleteTrack_WithPathTraversalInTrackId_ShouldReturnCleanProblemDetails(string maliciousTrackId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{maliciousTrackId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + 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); + + // Some payloads are normalized away by the server before routing, producing an empty-body response, while others reach the handler and + // produce a clean problem details; either way, the status is asserted unconditionally, so an empty-bodied 500 cannot satisfy the test. + Assert.True(response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.UnprocessableEntity, + $"Unexpected status code {response.StatusCode}."); + Assert.NotEqual(StatusCodes.Status500InternalServerError, (int)response.StatusCode); + + // When the payload reaches the handler, the failure must still be a clean, generic problem. + if (!string.IsNullOrWhiteSpace(content)) + { + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.NotEmpty(problemDetails.RootElement.ToString()); + } + } + + [Fact] + public async Task DeleteTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + [Fact] + public async Task DeleteTrack_WhenTrackBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + (Guid ownLibraryId, _, _, _) = await SeedLibraryArtistAlbumAndTrackAsync(actingUserId); + + // The track lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + (_, Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(victimUserId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's track is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId)); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + AlbumEntity album = _albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: "News of the World", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + TrackEntity track = _trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", + title: "We Are the Champions", + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Albums.Add(album); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointTests.cs new file mode 100644 index 00000000..905d7374 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointTests.cs @@ -0,0 +1,285 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTrackEndpointTests(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 GetTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetTrack_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"); + + // Assert + // The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetTrack_WithSQLInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}"); + + // Assert + // The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousArtistId, content, StringComparison.Ordinal); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetTrack_WithSQLInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}"); + + // Assert + // The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean + // validation error instead of failing the request binding. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousAlbumId, content, StringComparison.Ordinal); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt + public async Task GetTrack_WithSQLInjectionInTrackId_ShouldNotCorruptOrLeakData(string maliciousTrackId) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}"); + + // Assert + // The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousTrackId, content, StringComparison.Ordinal); + Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + + } + + [Fact] + public async Task GetTrack_WhenTrackBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded other user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return userId; + } + + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Reissues", libraryType: LibraryType.Music, contentLocations: [])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false)); + AlbumEntity album = _albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: "News of the World", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + TrackEntity track = _trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + path: $"/music/queen/we-are-the-champions-{Guid.NewGuid():N}.flac", + title: "We Are the Champions", + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + dbContext.Albums.Add(album); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs new file mode 100644 index 00000000..564d78e4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -0,0 +1,356 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackEndpointTests : IClassFixture, IDisposable +{ + private static readonly string s_contentRootPath = Path.Combine(Path.GetTempPath(), "lumina-security-update-track-tests"); + + private readonly LuminaApiFactory _apiFactory; + private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateTrackEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateTrack_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(401, 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateTrack_WithSQLInjectionInBody_ShouldNotCorruptOrLeakData(string maliciousTitle) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid libraryId = Guid.NewGuid(); + SeedLibrary(libraryId, userId); + (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), + moods: [], + isrcs: [], + contributors: [], + ratings: []); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request); + + // Assert + // The malicious title passes validation, reaches the parameterized update, and is persisted verbatim: if it were + // concatenated into raw SQL, the update would fail and the track would not be updated. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + TrackEntity? storedTrack = await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == trackId); + Assert.NotNull(storedTrack); + Assert.Equal(maliciousTitle, storedTrack!.Title); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateTrack_WithSQLInjectionInLibraryRouteId_ShouldRemainSecure(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousLibraryId, "LibraryIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateTrack_WithSQLInjectionInArtistRouteId_ShouldRemainSecure(string maliciousArtistId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Uri.EscapeDataString(maliciousArtistId)}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousArtistId, "ArtistIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateTrack_WithSQLInjectionInAlbumRouteId_ShouldRemainSecure(string maliciousAlbumId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Uri.EscapeDataString(maliciousAlbumId)}/tracks/{Guid.NewGuid()}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousAlbumId, "AlbumIdCannotBeEmpty"); + } + + [Theory] + [InlineData("'; DROP TABLE Tracks; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateTrack_WithSQLInjectionInTrackRouteId_ShouldRemainSecure(string maliciousTrackId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Uri.EscapeDataString(maliciousTrackId)}", request); + + // Assert + await AssertCleanValidationErrorAsync(response, maliciousTrackId, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdateTrack_WhenArtistDoesNotExist_ShouldReturnNotFoundWithoutLeakingInternals() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + Guid libraryId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Hash", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + } + + [Fact] + public async Task UpdateTrack_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid libraryId = Guid.NewGuid(); + SeedLibrary(libraryId, ownerId); + (Guid artistId, Guid albumId, Guid trackId) = SeedArtistGraph(libraryId); + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + _seededUsernames.Add(requesterUsername); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task UpdateTrack_WhenTrackBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutLeakingOrModifyingIt() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(actingUsername); + Guid ownLibraryId = Guid.NewGuid(); + SeedLibrary(ownLibraryId, actingUserId); + + // The track lives in a library owned by another user, and is referenced through the acting user's own library route. + HttpClient victimClient = _apiFactory.CreateClient(); + (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient); + _seededUsernames.Add(victimUsername); + Guid victimLibraryId = Guid.NewGuid(); + SeedLibrary(victimLibraryId, victimUserId); + (Guid victimArtistId, Guid victimAlbumId, Guid victimTrackId) = SeedArtistGraph(victimLibraryId); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: "Hijacked")); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{ownLibraryId}/artists/{victimArtistId}/albums/{victimAlbumId}/tracks/{victimTrackId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Equal("ArtistNotFound", problemDetails.RootElement.GetProperty("detail").GetString()); + + // The other user's track is untouched. + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Tracks.FirstOrDefaultAsync(track => track.Id == victimTrackId)); + } + + /// + /// Asserts that the response is a clean validation problem details that neither leaks internals nor echoes the injected payload. + /// + /// The HTTP response to assert. + /// The injected payload that must never be echoed back. + /// The validation error code expected in the response. + private static async Task AssertCleanValidationErrorAsync(HttpResponseMessage response, string injectedPayload, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(injectedPayload, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains(expectedErrorCode, content, StringComparison.Ordinal); + } + + /// + /// Seeds a media library of type music owned by , whose single content location is the test content root path. + /// + /// The Id of the media library to seed. + /// The Id of the user that owns the media library. + private void SeedLibrary(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Security Audio Library", libraryType: LibraryType.Music, contentLocations: [s_contentRootPath])); + dbContext.SaveChanges(); + _seededLibraryIds.Add(libraryId); + } + + /// + /// Seeds an artist that owns a single album, which in turn owns a single track, all belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The Ids of the seeded artist, album and track. + private (Guid artistId, Guid albumId, Guid trackId) SeedArtistGraph(Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: Path.Combine(s_contentRootPath, "bohemian-rhapsody.flac"), includeMetadata: false); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, tracks: [track], includeMetadata: false); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, albums: [album], includeContributors: false); + dbContext.Artists.Add(artist); + dbContext.SaveChanges(); + return (artist.Id, albumId, trackId); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List artists = [.. dbContext.Artists.Where(artist => _seededLibraryIds.Contains(artist.LibraryId))]; + dbContext.Artists.RemoveRange(artists); + List libraries = [.. dbContext.Libraries.Where(library => _seededLibraryIds.Contains(library.Id))]; + dbContext.Libraries.RemoveRange(libraries); + dbContext.SaveChanges(); + } + + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 5f8031dc..7125f9d8 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1,15 +1,19 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -26,7 +30,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo public class AddBookEndpointTests : IClassFixture, IDisposable { private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; private readonly AddBookRequestFixture _addBookRequestFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -39,6 +46,61 @@ public class AddBookEndpointTests : IClassFixture, IDisposable public AddBookEndpointTests(LuminaApiFactory apiFactory) { _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddBookRequest request = _addBookRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request); + + // 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/books", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task AddBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + AddBookRequest request = _addBookRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } [Theory] @@ -50,11 +112,18 @@ public class AddBookEndpointTests : IClassFixture, IDisposable HttpClient client = _apiFactory.CreateClient(); (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); Guid libraryId = Guid.NewGuid(); - await _apiFactory.SeedLibraryAsync(libraryId, userId); - AddBookRequest request = _addBookRequestFixture.Create(libraryId: libraryId, path: maliciousPath); + string contentLocation = Path.GetTempPath(); + string injectedPath = Path.Combine(contentLocation, $"{maliciousPath}.epub"); + using (IServiceScope seedScope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService(); + seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation])); + await seedDbContext.SaveChangesAsync(); + } + AddBookRequest request = _addBookRequestFixture.Create(path: injectedPath, contributors: []); // Act - HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/books", request); + HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request); // Assert // the malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted @@ -71,6 +140,71 @@ public class AddBookEndpointTests : IClassFixture, IDisposable await _apiFactory.RemoveTestUserAsync(username); } + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddBook_WithSQLInjectionInBody_ShouldNotCorruptOrDeleteData(string maliciousTitle) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + string contentLocation = Path.GetTempPath(); + using (IServiceScope seedScope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService(); + seedDbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [contentLocation])); + await seedDbContext.SaveChangesAsync(); + } + string bookPath = Path.Combine(contentLocation, $"{Guid.NewGuid()}.epub"); + AddBookRequest request = _addBookRequestFixture.Create(path: bookPath, metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle), contributors: []); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request); + + // Assert + // the malicious title passes the authenticated handler, reaches the parameterized insert, and is persisted + // verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + BookEntity storedBook = await dbContext.Books.SingleAsync(book => book.LibraryId == libraryId); + Assert.Equal(maliciousTitle, storedBook.Title); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddBook_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + AddBookRequest request = _addBookRequestFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books", request); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + /// /// Disposes API factory resources. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs index 4088d216..5e6e2248 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -29,13 +29,13 @@ public class GetBookEndpointTests : IClassFixture } [Fact] - public async Task GetBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + public async Task GetBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange HttpClient client = _apiFactory.CreateClient(); // Act - HttpResponseMessage response = await client.GetAsync($"/api/v1/books/{Guid.NewGuid()}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -53,15 +53,17 @@ public class GetBookEndpointTests : IClassFixture (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); // Act - HttpResponseMessage response = await client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Uri.EscapeDataString(maliciousBookId)}"); // Assert - // The unparseable route value becomes an empty book Id, which the query validator reports as a missing book Id. + // The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean + // validation error instead of failing the request binding. Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal); using JsonDocument problemDetails = JsonDocument.Parse(content); Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 6e3132d7..3c7d99b6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -40,7 +40,7 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl public async Task GetBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1/books"); + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -52,7 +52,7 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl 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/books", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } @@ -69,12 +69,13 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl await _apiFactory.SeedBookAsync(libraryId, "Book A"); // Act - HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); // Assert response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal); // the injected statement must never be executed: the Books table and the seeded rows must still be there using IServiceScope scope = _apiFactory.Services.CreateScope(); @@ -84,6 +85,64 @@ public class GetBooksEndpointTests : IClassFixture, IDisposabl await _apiFactory.RemoveTestUserAsync(username); } + [Fact] + public async Task GetBooks_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBooks_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books"); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + /// /// Disposes API factory resources. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index bf387226..921f6122 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -41,7 +41,7 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo public async Task GetBooksLite_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Act - HttpResponseMessage response = await _client.GetAsync("/api/v1/books/lite"); + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -53,7 +53,7 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo 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/books/lite", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/lite", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } @@ -70,12 +70,13 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo await _apiFactory.SeedBookAsync(libraryId, "Book A"); // Act - HttpResponseMessage response = await client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); // Assert response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousSearchTerm, content, StringComparison.Ordinal); // the injected statement must never be executed: the Books table and the seeded rows must still be there using IServiceScope scope = _apiFactory.Services.CreateScope(); @@ -85,6 +86,64 @@ public class GetBooksLiteEndpointTests : IClassFixture, IDispo await _apiFactory.RemoveTestUserAsync(username); } + [Fact] + public async Task GetBooksLite_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/books/lite"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBooksLite_WithSQLInjectionInRouteId_ShouldNotCorruptOrLeakData(string maliciousLibraryId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid _, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/lite"); + + // Assert + // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the query + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal); + using JsonDocument problemDetails = JsonDocument.Parse(content); + Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString()); + Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); + + await _apiFactory.RemoveTestUserAsync(username); + } + /// /// Disposes API factory resources. /// diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index f0d2cab7..113292c6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -1,9 +1,16 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; +using System.Net.Http; using System.Text.Json; +using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; @@ -14,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo [ExcludeFromCodeCoverage] public class GetReadingAvailabilityEndpointTests : IClassFixture { - private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -26,14 +33,17 @@ public class GetReadingAvailabilityEndpointTests : IClassFixtureInjected in-memory API factory. public GetReadingAvailabilityEndpointTests(LuminaApiFactory apiFactory) { - _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; } [Fact] public async Task GetReadingAvailability_WhenUnauthorized_ShouldReturnUnauthorizedResult() { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/availability"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/availability"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -52,15 +62,60 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + + // Act + HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/availability"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index e4841be8..46b2e87c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; @@ -18,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo [ExcludeFromCodeCoverage] public class GetReadingManifestEndpointTests : IClassFixture { - private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -30,14 +33,17 @@ public class GetReadingManifestEndpointTests : IClassFixture /// Injected in-memory API factory. public GetReadingManifestEndpointTests(LuminaApiFactory apiFactory) { - _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; } [Fact] public async Task GetReadingManifest_WhenUnauthorized_ShouldReturnUnauthorizedResult() { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/manifest"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/manifest"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -56,15 +62,60 @@ public class GetReadingManifestEndpointTests : IClassFixture [InlineData("'; DROP TABLE Books--")] // destructive injection public async Task GetReadingManifest_WithSQLInjectionInBookId_ShouldNotLeakDatabaseDetails(string maliciousBookId) { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}/reading/manifest"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}/reading/manifest"); string content = await response.Content.ReadAsStringAsync(); // Assert - // the {bookId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler + // The authenticated request reaches validation, where the unparseable route Id is reported as a clean validation error, + // without executing the injected payload or leaking database details. + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousBookId, content, StringComparison.Ordinal); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Fact] + public async Task GetReadingManifest_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + await _apiFactory.SeedBookAsync(libraryId, "Other User Book"); + Guid bookId; + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + + // Act + HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/manifest"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs index d1e2ba8f..198f5e43 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResource/GetReadingResourceEndpointTests.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; @@ -18,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo [ExcludeFromCodeCoverage] public class GetReadingResourceEndpointTests : IClassFixture { - private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -30,14 +33,17 @@ public class GetReadingResourceEndpointTests : IClassFixture /// Injected in-memory API factory. public GetReadingResourceEndpointTests(LuminaApiFactory apiFactory) { - _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; } [Fact] public async Task GetReadingResource_WhenUnauthorized_ShouldReturnUnauthorizedResult() { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/cover"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/resources/cover"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -56,15 +62,25 @@ public class GetReadingResourceEndpointTests : IClassFixture [InlineData("'; DROP TABLE Books--")] // destructive injection public async Task GetReadingResource_WithSQLInjectionInResourceKey_ShouldNotLeakDatabaseDetails(string maliciousResourceKey) { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/{Uri.EscapeDataString(maliciousResourceKey)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/{Uri.EscapeDataString(maliciousResourceKey)}"); string content = await response.Content.ReadAsStringAsync(); // Assert + // The authenticated request reaches the handler and the database, where the book does not exist, so the request fails + // cleanly without executing the injected payload or leaking database details. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousResourceKey, content, StringComparison.Ordinal); + + await _apiFactory.RemoveTestUserAsync(username); } [Theory] @@ -72,13 +88,56 @@ public class GetReadingResourceEndpointTests : IClassFixture [InlineData("..%2F..%2Fetc%2Fpasswd")] // encoded directory traversal public async Task GetReadingResource_WithPathTraversalInResourceKey_ShouldNotExposeFilesystemPaths(string traversalPayload) { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/resources/{traversalPayload}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/resources/{traversalPayload}"); string content = await response.Content.ReadAsStringAsync(); // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.DoesNotContain("etc/passwd", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.Ordinal); Assert.DoesNotContain("Stack Trace", content, StringComparison.Ordinal); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Fact] + public async Task GetReadingResource_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + await _apiFactory.SeedBookAsync(libraryId, "Other User Book"); + Guid bookId; + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + + // Act + HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/resources/cover"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index 89b8842f..86bb0fc6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; @@ -18,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo [ExcludeFromCodeCoverage] public class GetReadingSectionEndpointTests : IClassFixture { - private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -30,14 +33,17 @@ public class GetReadingSectionEndpointTests : IClassFixture /// Injected in-memory API factory. public GetReadingSectionEndpointTests(LuminaApiFactory apiFactory) { - _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; } [Fact] public async Task GetReadingSection_WhenUnauthorized_ShouldReturnUnauthorizedResult() { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/chapter-1"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/reading/sections/chapter-1"); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); @@ -56,15 +62,25 @@ public class GetReadingSectionEndpointTests : IClassFixture [InlineData("'; DROP TABLE Books--")] // destructive injection public async Task GetReadingSection_WithSQLInjectionInLocationRef_ShouldNotLeakDatabaseDetails(string maliciousLocationRef) { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/{Uri.EscapeDataString(maliciousLocationRef)}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/{Uri.EscapeDataString(maliciousLocationRef)}"); string content = await response.Content.ReadAsStringAsync(); // Assert + // The authenticated request reaches the handler and the database, where the book does not exist, so the request fails + // cleanly without executing the injected payload or leaking database details. + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(maliciousLocationRef, content, StringComparison.Ordinal); + + await _apiFactory.RemoveTestUserAsync(username); } [Theory] @@ -72,13 +88,56 @@ public class GetReadingSectionEndpointTests : IClassFixture [InlineData("..%2F..%2Fetc%2Fpasswd")] // encoded directory traversal public async Task GetReadingSection_WithPathTraversalInLocationRef_ShouldNotExposeFilesystemPaths(string traversalPayload) { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + // Act - HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Guid.NewGuid()}/reading/sections/{traversalPayload}"); + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/reading/sections/{traversalPayload}"); string content = await response.Content.ReadAsStringAsync(); // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.DoesNotContain("etc/passwd", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.Ordinal); Assert.DoesNotContain("Stack Trace", content, StringComparison.Ordinal); + + await _apiFactory.RemoveTestUserAsync(username); + } + + [Fact] + public async Task GetReadingSection_WhenUserDoesNotOwnTheBookLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + await _apiFactory.SeedBookAsync(libraryId, "Other User Book"); + Guid bookId; + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + + // Act + HttpResponseMessage response = await requesterClient.GetAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/reading/sections/chapter-1"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs index 3864d177..3bcdc011 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -2,10 +2,15 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -35,19 +40,27 @@ public class UpdateBookEndpointTests : IClassFixture } [Fact] - public async Task UpdateBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + public async Task UpdateBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange HttpClient client = _apiFactory.CreateClient(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/books/{bookId}", problemDetails["instance"].GetProperty("value").GetString()); } [Theory] @@ -58,10 +71,12 @@ public class UpdateBookEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: maliciousTitle)); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{request.Id}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); // Assert // The injected title is validated and handled by the parameterized update flow: the route book does not exist, @@ -83,15 +98,16 @@ public class UpdateBookEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{Uri.EscapeDataString(maliciousBookId)}", request); // Assert // The route is authoritative and its raw value is kept as a string, so an unparseable route Id reaches the command - // mapping and becomes Guid.Empty, which the command validator reports as a clean validation error. The response must - // not leak stack traces, database details, or the injected payload, and the body Id never redirects the update. + // validator, which reports it as a clean validation error. The response must not leak stack traces, database details, + // or the injected payload. Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); @@ -105,16 +121,17 @@ public class UpdateBookEndpointTests : IClassFixture } [Fact] - public async Task UpdateBook_WhenRouteBookDoesNotExistEvenIfBodyIdDiffers_ShouldReturnNotFound() + public async Task UpdateBook_WhenRouteBookDoesNotExist_ShouldReturnNotFound() { // Arrange HttpClient client = _apiFactory.CreateClient(); (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); UpdateBookRequest request = _updateBookRequestFixture.Create(); // Act - HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/books/{routeId}", request); + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{routeId}", request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -127,4 +144,41 @@ public class UpdateBookEndpointTests : IClassFixture await _apiFactory.RemoveTestUserAsync(username); } + + [Fact] + public async Task UpdateBook_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + await _apiFactory.SeedBookAsync(libraryId, "Other User Book"); + Guid bookId; + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + UpdateBookRequest request = _updateBookRequestFixture.Create(); + + // Act + HttpResponseMessage response = await requesterClient.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/books/{bookId}", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs index a2d91107..204b4d55 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -1,8 +1,13 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; @@ -31,19 +36,64 @@ public class UpdateBookCoverEndpointTests : IClassFixture } [Fact] - public async Task UpdateBookCover_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + public async Task UpdateBookCover_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange HttpClient client = _apiFactory.CreateClient(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); MultipartFormDataContent form = CreateCoverForm("cover.jpg"); // Act - HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", form); + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form); // Assert Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", problemDetails["instance"].GetProperty("value").GetString()); + } + + [Fact] + public async Task UpdateBookCover_WhenUserDoesNotOwnTheLibrary_ShouldReturnForbidden() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, ownerId); + await _apiFactory.SeedBookAsync(libraryId, "Other User Book"); + Guid bookId; + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + bookId = dbContext.Books.Single(book => book.LibraryId == libraryId).Id; + } + + HttpClient requesterClient = _apiFactory.CreateClient(); + (Guid _, string requesterUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(requesterClient); + MultipartFormDataContent form = CreateCoverForm("cover.jpg"); + + // Act + HttpResponseMessage response = await requesterClient.PutAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/cover", form); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } [Theory] @@ -57,7 +107,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture MultipartFormDataContent form = CreateCoverForm("cover.jpg"); // Act - HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}/cover", form); + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Uri.EscapeDataString(maliciousBookId)}/cover", form); // Assert // The unparseable route value becomes an empty book Id, which the command validator reports as a missing book Id. @@ -81,7 +131,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture MultipartFormDataContent form = CreateCoverForm("..\\..\\evil.jpg"); // Act - HttpResponseMessage response = await client.PutAsync($"/api/v1/books/{Guid.NewGuid()}/cover", form); + HttpResponseMessage response = await client.PutAsync($"/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{Guid.NewGuid()}/cover", form); // Assert // The book does not exist, so the handler returns a clean not found response before the uploaded file name is used. diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs index 7544cfa9..94b344c9 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -247,7 +247,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable string content = await response.Content.ReadAsStringAsync(); // Assert - Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); Assert.DoesNotContain("SQL", content); Assert.DoesNotContain("Exception", content); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 447cf96e..cee285ae 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -127,7 +127,7 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl string content = await response.Content.ReadAsStringAsync(); // Assert - Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); Assert.DoesNotContain("SQL", content); Assert.DoesNotContain("Exception", content); Assert.DoesNotContain("password", content); @@ -156,7 +156,7 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl string content = await response.Content.ReadAsStringAsync(); // Assert - Assert.Equal(HttpStatusCode.UnprocessableContent, response.StatusCode); + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); Assert.DoesNotContain(weakPassword, content); // shouldn't leak the actual password } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs index 89ecad1e..ae410e05 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -1,10 +1,25 @@ #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.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Requests.Authorization; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; +using System.Net.Http; +using System.Net.Http.Json; using System.Text; using System.Text.Json; +using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Authorization; @@ -13,13 +28,22 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A /// Contains security tests for the class. ///
[ExcludeFromCodeCoverage] -public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture +public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture, IAsyncDisposable { private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + private Guid _adminUserId; + private Guid _seededRoleId; + private Guid _seededPermissionId; /// /// Initializes a new instance of the class. @@ -27,6 +51,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixtureInjected in-memory API factory. public UpdateUserRoleAndPermissionsEndpointTests(LuminaApiFactory apiFactory) { + _apiFactory = apiFactory; _client = apiFactory.CreateClient(); } @@ -53,4 +78,205 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture? problemDetails = JsonSerializer.Deserialize>(responseContent, _jsonOptions); + Assert.NotNull(problemDetails); + 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.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.DoesNotContain("password", responseContent, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", responseContent, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", responseContent, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledByAdminWithValidData_ShouldUpdateRoleAndPermissions() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + UserEntity targetUser = await SeedTargetUserAsync(); + RoleEntity editorRole = await SeedRoleAsync("Editor"); + PermissionEntity permission = await SeedPermissionAsync(AuthorizationPermission.CanDeleteUsers); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( + userId: targetUser.Id, + roleId: editorRole.Id, + permissions: [permission.Id] + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/auth/users/{targetUser.Id}/role-and-permissions", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument authorizationResponse = JsonDocument.Parse(content); + Assert.Equal(targetUser.Id, authorizationResponse.RootElement.GetProperty("userId").GetGuid()); + Assert.Equal("Editor", authorizationResponse.RootElement.GetProperty("role").GetString()); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity? updatedUser = await dbContext.Users + .Include(user => user.UserRole).ThenInclude(userRole => userRole!.Role) + .Include(user => user.UserPermissions) + .FirstOrDefaultAsync(user => user.Id == targetUser.Id); + Assert.NotNull(updatedUser); + Assert.Equal("Editor", updatedUser!.UserRole!.Role.RoleName); + Assert.Contains(updatedUser.UserPermissions, userPermission => userPermission.PermissionId == permission.Id); + } + + [Theory] + [InlineData("'; DROP TABLE UserRoles; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateUserRoleAndPermissions_WithInjectionInUserIdRouteSegment_ShouldNotLeakOrExecuteSql(string maliciousUserId) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( + userId: Guid.NewGuid(), + roleId: Guid.NewGuid(), + permissions: [] + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/auth/users/{Uri.EscapeDataString(maliciousUserId)}/role-and-permissions", request); + + // Assert + // note: the {userId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler + // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding failure into a + // 500 response instead of 400/422 (pre-existing production bug, not fixed here), and that body leaks the binding exception details + // note: what matters is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("'; DROP TABLE UserPermissions; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateUserRoleAndPermissions_WithInjectionInPermissionsBody_ShouldNotLeakOrExecuteSql(string maliciousPermissionId) + { + // Arrange + // authenticate as an admin and seed the target user, so a well-formed body would reach the handler and be authorized + HttpClient client = _apiFactory.CreateClient(); + _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + UserEntity targetUser = await SeedTargetUserAsync(); + string jsonBody = $"{{\"userId\":\"{targetUser.Id}\",\"roleId\":\"{Guid.NewGuid()}\",\"permissions\":[\"{maliciousPermissionId}\"]}}"; + + // Act + HttpResponseMessage response = await client.PutAsync( + $"/api/v1/auth/users/{targetUser.Id}/role-and-permissions", + new StringContent(jsonBody, Encoding.UTF8, "application/json")); + + // Assert + // Note: the permission Ids are Guid-typed, so the malicious value fails model binding before it reaches the handler. + // Note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding failure into a + // 500 response instead of 400/422 (pre-existing production bug, not fixed here), and that body leaks the binding exception details. + // Note: what matters is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface. + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a user whose role and permissions are updated, and traces its username for cleanup. + /// + /// The seeded user. + private async Task SeedTargetUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + string username = $"targetuser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: Guid.NewGuid(), username: username, password: "HashedPassword"); + user.TotpSecret = null; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return user; + } + + /// + /// Seeds a role that is assigned to the updated user, and traces it for cleanup. + /// + /// The name of the role to seed. + /// The seeded role. + private async Task SeedRoleAsync(string roleName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + _seededRoleId = Guid.NewGuid(); + RoleEntity role = _roleEntityFixture.Create(id: _seededRoleId, roleName: roleName); + dbContext.Roles.Add(role); + await dbContext.SaveChangesAsync(); + return role; + } + + /// + /// Seeds a permission that is assigned to the updated user, and traces it for cleanup. + /// + /// The permission to seed. + /// The seeded permission. + private async Task SeedPermissionAsync(AuthorizationPermission permissionName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + _seededPermissionId = Guid.NewGuid(); + PermissionEntity permission = _permissionEntityFixture.Create(id: _seededPermissionId, permissionName: permissionName); + dbContext.Permissions.Add(permission); + await dbContext.SaveChangesAsync(); + return permission; + } + + /// + /// Disposes API factory resources. + /// + public async ValueTask DisposeAsync() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + await _apiFactory.RemoveTestUserAsync(username).ConfigureAwait(false); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + if (_seededRoleId != Guid.Empty) + { + RoleEntity? role = await dbContext.Roles.FirstOrDefaultAsync(candidate => candidate.Id == _seededRoleId); + if (role is not null) + dbContext.Roles.Remove(role); + } + if (_seededPermissionId != Guid.Empty) + { + PermissionEntity? permission = await dbContext.Permissions.FirstOrDefaultAsync(candidate => candidate.Id == _seededPermissionId); + if (permission is not null) + dbContext.Permissions.Remove(permission); + } + await dbContext.SaveChangesAsync(); + if (_adminUserId != Guid.Empty) + await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false); + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs index 0ac6b729..836b10a2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -50,10 +50,10 @@ public class GetDirectoriesEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(maliciousPath)}&shouldIncludeHiddenElements=False"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(maliciousPath)}&shouldIncludeHiddenElements=false"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs index c34cfae1..6dc38ea1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -50,10 +50,10 @@ public class GetFilesEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(maliciousPath)}&shouldIncludeHiddenElements=False"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(maliciousPath)}&shouldIncludeHiddenElements=false"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs index c24e173c..d2a5f9cb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -51,10 +51,10 @@ public class CheckPathExistsEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&shouldIncludeHiddenElements=False"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&shouldIncludeHiddenElements=false"); getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Act diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs index 8f7d8083..079263c2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs @@ -44,7 +44,7 @@ public class GetBookDetailsEndpointTests : IClassFixture // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); - Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/", StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.OrdinalIgnoreCase)); } [Theory] @@ -54,13 +54,14 @@ public class GetBookDetailsEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); string normalizedBookId = Guid.Empty.ToString(); BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); - _apiFactory.ApiClientStub.RegisterGetResponse($"books/{normalizedBookId}", expectedBook); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/books/{normalizedBookId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); // Act - HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(maliciousBookId)}/api-get-book"); + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(maliciousBookId)}/api-get-book?libraryId={libraryId}"); string content = await response.Content.ReadAsStringAsync(); // Assert @@ -73,6 +74,6 @@ public class GetBookDetailsEndpointTests : IClassFixture Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); - Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"books/{normalizedBookId}"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/books/{normalizedBookId}"); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs index ec70b8fe..d56846ea 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -41,7 +41,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture // Assert Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); - Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/lite", StringComparison.Ordinal)); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.Ordinal)); } [Theory] @@ -52,7 +52,7 @@ public class GetLibraryItemsEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid libraryId = Guid.NewGuid(); - string expectedEndpoint = $"books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False"; + string expectedEndpoint = $"libraries/{libraryId}/books/lite?searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False"; _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedBookLiteDtoFixture.Create()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=false"); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index 75fa6a13..c9f132d2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -45,10 +45,11 @@ public class SaveBookEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid bodyId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); string normalizedBookId = Guid.Empty.ToString(); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{normalizedBookId}", _bookDetailsDtoFixture.Create()); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{normalizedBookId}", _bookDetailsDtoFixture.Create()); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId)); + HttpRequestMessage saveRequest = CreateSaveRequest(maliciousBookId, _updateBookRequestFixture.Create(id: bodyId, libraryId: libraryId)); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); // Act @@ -63,8 +64,8 @@ public class SaveBookEndpointTests : IClassFixture Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Id == normalizedBookId); - Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bodyId}"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{normalizedBookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.BookId == normalizedBookId); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bodyId}"); } [Theory] @@ -75,11 +76,12 @@ public class SaveBookEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId); + Guid libraryId = Guid.NewGuid(); + UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId); request.Metadata!.Title = maliciousTitle; BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: bookId); expectedBook.Metadata!.Title = maliciousTitle; - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{bookId}", expectedBook); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}", expectedBook); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -93,7 +95,7 @@ public class SaveBookEndpointTests : IClassFixture Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle); } [Fact] diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs index bf3de484..afaa7654 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -37,9 +37,10 @@ public class UpdateBookCoverEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{Guid.Empty}/cover", "/media/books/cover.png"); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{Guid.Empty}/cover", "/media/books/cover.png"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousBookId, "cover.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(maliciousBookId, libraryId, "cover.png"); uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); // Act @@ -51,7 +52,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); - Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"books/{Guid.Empty}/cover"); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{Guid.Empty}/cover"); } [Fact] @@ -59,9 +60,11 @@ public class UpdateBookCoverEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPutResponse($"books/{Guid.NewGuid()}/cover", "/media/books/cover.png"); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPutResponse($"libraries/{libraryId}/books/{bookId}/cover", "/media/books/cover.png"); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), "..\\..\\evil.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(bookId.ToString(), libraryId, "..\\..\\evil.png"); uploadRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); // Act @@ -80,7 +83,7 @@ public class UpdateBookCoverEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); - HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), "cover.png"); + HttpRequestMessage uploadRequest = CreateUploadRequest(Guid.NewGuid().ToString(), Guid.NewGuid(), "cover.png"); // Act HttpResponseMessage response = await anonymousClient.SendAsync(uploadRequest); @@ -94,15 +97,16 @@ public class UpdateBookCoverEndpointTests : IClassFixture /// Builds the multipart PUT request that uploads a cover to the book identified by . /// /// The route Id of the book whose cover is uploaded. + /// The Id of the media library the book belongs to. /// The name of the uploaded file. /// The configured upload request. - private static HttpRequestMessage CreateUploadRequest(string bookId, string fileName) + private static HttpRequestMessage CreateUploadRequest(string bookId, Guid libraryId, string fileName) { MultipartFormDataContent form = []; ByteArrayContent fileContent = new(Encoding.UTF8.GetBytes("fake cover payload")); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); form.Add(fileContent, "cover", fileName); - return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-update-cover") + return new HttpRequestMessage(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-update-cover?libraryId={libraryId}") { Content = form }; 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 new file mode 100644 index 00000000..f73d1053 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/LanguageInfoDtoMappingTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoDtoMappingTests +{ + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteLanguageInfoDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + LanguageInfoDto dto = _languageInfoDtoFixture.Create(languageCode: "EN", languageName: "English", nativeName: "English"); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("en", result.Value.LanguageCode); + Assert.Equal(dto.LanguageName, result.Value.LanguageName); + Assert.True(result.Value.NativeName.HasValue); + Assert.Equal(dto.NativeName, result.Value.NativeName.Value); + } + + [Fact] + public void ToDomainEntity_WhenNativeNameIsMissing_ShouldMapWithoutNativeName() + { + // Arrange + LanguageInfoDto dto = _languageInfoDtoFixture.Create(includeNativeName: false); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dto.LanguageCode!.ToLowerInvariant(), result.Value.LanguageCode); + Assert.Equal(dto.LanguageName, result.Value.LanguageName); + Assert.False(result.Value.NativeName.HasValue); + } +} 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 new file mode 100644 index 00000000..8d613e8a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/ReleaseInfoDtoMappingTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoDtoMappingTests +{ + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteReleaseInfoDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ReleaseInfoDto dto = _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 2000, + reReleaseDate: new DateOnly(2010, 1, 1), + reReleaseYear: 2010, + releaseCountry: ReleaseCountry.AD, + releaseVersion: "Director's Cut"); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.True(result.Value.OriginalReleaseDate.HasValue); + Assert.Equal(dto.OriginalReleaseDate!.Value, result.Value.OriginalReleaseDate.Value); + Assert.True(result.Value.OriginalReleaseYear.HasValue); + Assert.Equal(dto.OriginalReleaseYear!.Value, result.Value.OriginalReleaseYear.Value); + Assert.True(result.Value.ReReleaseDate.HasValue); + Assert.Equal(dto.ReReleaseDate!.Value, result.Value.ReReleaseDate.Value); + Assert.True(result.Value.ReReleaseYear.HasValue); + Assert.Equal(dto.ReReleaseYear!.Value, result.Value.ReReleaseYear.Value); + Assert.True(result.Value.ReleaseCountry.HasValue); + Assert.Equal(dto.ReleaseCountry!.Value, result.Value.ReleaseCountry.Value); + Assert.True(result.Value.ReleaseVersion.HasValue); + Assert.Equal(dto.ReleaseVersion, result.Value.ReleaseVersion.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues() + { + // Arrange + ReleaseInfoDto dto = _releaseInfoDtoFixture.Create(); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.OriginalReleaseDate.HasValue); + Assert.False(result.Value.OriginalReleaseYear.HasValue); + Assert.False(result.Value.ReReleaseDate.HasValue); + Assert.False(result.Value.ReReleaseYear.HasValue); + Assert.False(result.Value.ReleaseCountry.HasValue); + Assert.False(result.Value.ReleaseVersion.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenOriginalReleaseDateAndYearDoNotMatch_ShouldReturnError() + { + // Arrange + ReleaseInfoDto dto = _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2025, 1, 1), + originalReleaseYear: 2024); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ToDomainEntity_WhenReReleaseDateAndYearDoNotMatch_ShouldReturnError() + { + // Arrange + ReleaseInfoDto dto = _releaseInfoDtoFixture.Create( + reReleaseDate: new DateOnly(2025, 1, 1), + reReleaseYear: 2024); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs index 1e12bef4..6f6df435 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Directories/GetDirectoriesRequestMappingTests.cs @@ -28,6 +28,6 @@ public class GetDirectoriesRequestMappingTests // Assert Assert.NotNull(result); Assert.Equal(request.Path, result.Path); - Assert.Equal(request.IncludeHiddenElements, result.IncludeHiddenElements); + Assert.Equal(request.ShouldIncludeHiddenElements, result.ShouldIncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs index aafecb2d..69c7e5bb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetFilesRequestMappingTests.cs @@ -28,6 +28,6 @@ public class GetFilesRequestMappingTests // Assert Assert.NotNull(result); Assert.Equal(request.Path, result.Path); - Assert.Equal(request.IncludeHiddenElements, result.IncludeHiddenElements); + Assert.Equal(request.ShouldIncludeHiddenElements, result.ShouldIncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs index 41644ab7..24301f3d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Files/GetTreeFilesRequestMappingTests.cs @@ -28,6 +28,6 @@ public class GetTreeFilesRequestMappingTests // Assert Assert.NotNull(result); Assert.Equal(request.Path, result.Path); - Assert.Equal(request.IncludeHiddenElements, result.IncludeHiddenElements); + Assert.Equal(request.ShouldIncludeHiddenElements, result.ShouldIncludeHiddenElements); } } 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 2ee1b6ab..0cc417ea 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 @@ -30,17 +30,17 @@ public class CheckPathExistsRequestMappingTests // Assert Assert.NotNull(result); Assert.Equal(request.Path, result.Path); - Assert.Equal(request.IncludeHiddenElements, result.IncludeHiddenElements); + Assert.Equal(request.ShouldIncludeHiddenElements, result.ShouldIncludeHiddenElements); } [Theory] [InlineData("/home/user/documents", true)] [InlineData("C:\\Users\\Documents", false)] [InlineData("/var/www/html", true)] - public void ToQuery_WhenMappingWithDifferentPathsAndHiddenElementsFlag_ShouldMapCorrectly(string path, bool includeHiddenElements) + public void ToQuery_WhenMappingWithDifferentPathsAndHiddenElementsFlag_ShouldMapCorrectly(string path, bool shouldIncludeHiddenElements) { // Arrange - CheckPathExistsRequest request = new(path, includeHiddenElements); + CheckPathExistsRequest request = new(path, shouldIncludeHiddenElements); // Act CheckPathExistsQuery result = request.ToQuery(); @@ -48,7 +48,7 @@ public class CheckPathExistsRequestMappingTests // Assert Assert.NotNull(result); Assert.Equal(path, result.Path); - Assert.Equal(includeHiddenElements, result.IncludeHiddenElements); + Assert.Equal(shouldIncludeHiddenElements, result.ShouldIncludeHiddenElements); } [Fact] @@ -66,7 +66,7 @@ public class CheckPathExistsRequestMappingTests for (int i = 0; i < requests.Count; i++) { Assert.Equal(requests[i].Path, results[i].Path); - Assert.Equal(requests[i].IncludeHiddenElements, results[i].IncludeHiddenElements); + Assert.Equal(requests[i].ShouldIncludeHiddenElements, results[i].ShouldIncludeHiddenElements); } } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaContributors/MediaContributorReferenceDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaContributors/MediaContributorReferenceDtoMappingTests.cs new file mode 100644 index 00000000..7f23e391 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaContributors/MediaContributorReferenceDtoMappingTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaContributors; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaContributors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorReferenceDtoMappingTests +{ + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + [Fact] + public void ToBookDomainEntity_WhenMappingCompleteMediaContributorReferenceDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid contributorId = Guid.NewGuid(); + MediaContributorReferenceDto dto = _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author); + + // Act + Result result = dto.ToBookDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dto.ContributorId, result.Value.ContributorId.Value); + Assert.Equal(dto.Role, result.Value.Role); + } + + [Fact] + public void ToBookDomainEntities_WhenMappingMultipleValidMediaContributorReferenceDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = + [ + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Illustrator) + ]; + + // Act + IEnumerable> results = dtos.ToBookDomainEntities(); + + // Assert + Assert.NotNull(results); + Assert.Equal(dtos.Count, results.Count()); + + List> resultList = [.. results]; + Assert.All(resultList, result => Assert.False(result.IsFailure)); + Assert.Equal(dtos[0].ContributorId, resultList[0].Value.ContributorId.Value); + Assert.Equal(dtos[0].Role, resultList[0].Value.Role); + Assert.Equal(dtos[1].ContributorId, resultList[1].Value.ContributorId.Value); + Assert.Equal(dtos[1].Role, resultList[1].Value.Role); + } + + [Fact] + public void ToMusicDomainEntity_WhenMappingCompleteMediaContributorReferenceDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid contributorId = Guid.NewGuid(); + MediaContributorReferenceDto dto = _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Producer); + + // Act + Result result = dto.ToMusicDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dto.ContributorId, result.Value.ContributorId.Value); + Assert.Equal(dto.Role, result.Value.Role); + } + + [Fact] + public void ToMusicDomainEntities_WhenMappingMultipleValidMediaContributorReferenceDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = + [ + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Vocals), + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Guitar) + ]; + + // Act + IEnumerable> results = dtos.ToMusicDomainEntities(); + + // Assert + Assert.NotNull(results); + Assert.Equal(dtos.Count, results.Count()); + + List> resultList = [.. results]; + Assert.All(resultList, result => Assert.False(result.IsFailure)); + Assert.Equal(dtos[0].ContributorId, resultList[0].Value.ContributorId.Value); + Assert.Equal(dtos[0].Role, resultList[0].Value.Role); + Assert.Equal(dtos[1].ContributorId, resultList[1].Value.ContributorId.Value); + Assert.Equal(dtos[1].Role, resultList[1].Value.Role); + } +} 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 new file mode 100644 index 00000000..f327f806 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMappingTests.cs @@ -0,0 +1,211 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +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.Entities; +using System; +using System.Collections.Generic; +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 AddAlbumCommandMappingTests +{ + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + 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.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value); + Assert.Equal(command.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value); + Assert.Equal(command.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value); + Assert.Equal(command.Contributors!.Count, album.Contributors.Count); + Assert.Equal(command.Ratings!.Count, album.Ratings.Count); + Assert.Equal(command.Tracks!.Count, album.Tracks.Count); + } + + [Fact] + public void ToDomainEntity_WhenAlbumIdIsProvided_ShouldReuseTheProvidedAlbumId() + { + // Arrange + Guid albumId = Guid.NewGuid(); + AddAlbumCommand command = _addAlbumCommandFixture.Create(albumId: albumId); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(albumId, result.Value.Id.Value); + } + + [Fact] + public void ToDomainEntity_WhenAlbumIdIsNotProvided_ShouldMintANewAlbumId() + { + // Arrange + AddAlbumCommand firstCommand = _addAlbumCommandFixture.Create(); + AddAlbumCommand secondCommand = _addAlbumCommandFixture.Create(); + + // Act + Result firstResult = firstCommand.ToDomainEntity(); + Result secondResult = secondCommand.ToDomainEntity(); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + // Two independent mappings must mint two distinct album Ids, instead of both collapsing to the same default value. + Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create( + includeMediaFormat: false, + includeBarcode: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + contributors: [], + ratings: [], + tracks: []); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + Assert.Equal(command.Metadata!.Title, album.Metadata.Title); + Assert.False(album.MediaFormat.HasValue); + Assert.False(album.Barcode.HasValue); + Assert.False(album.CatalogNumber.HasValue); + Assert.False(album.MusicBrainzReleaseId.HasValue); + Assert.False(album.MusicBrainzReleaseGroupId.HasValue); + Assert.False(album.MusicBrainzReleaseArtistId.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create( + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenBarcodeCannotBeEmpty_ShouldReturnError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: string.Empty); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.BarcodeValueCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenBarcodeHasInvalidFormat_ShouldReturnError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: "not-a-barcode"); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.InvalidFormatForBarcode, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); + } + + [Fact] + public void ToDomainEntity_WhenTrackCreationFails_ShouldReturnError() + { + // Arrange + AddTrackCommand invalidTrack = _addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "invalid")]); + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [invalidTrack]); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Music.IsrcInvalidFormat.Description); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleCommands_ShouldMapEachCommand() + { + // Arrange + List commands = _addAlbumCommandFixture.CreateMany(3); + + // Act + List> results = [.. commands.ToDomainEntities()]; + + // Assert + Assert.Equal(commands.Count, results.Count); + Assert.All(results, result => Assert.False(result.IsFailure)); + for (int i = 0; i < commands.Count; i++) + { + Assert.Equal(commands[i].Metadata!.Title, results[i].Value.Metadata.Title); + Assert.Equal(commands[i].Tracks!.Count, results[i].Value.Tracks.Count); + } + } +} 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 new file mode 100644 index 00000000..8a38f7b6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMappingTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +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 AddAlbumRequestMappingTests +{ + private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + 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.MusicBrainzReleaseId, result.MusicBrainzReleaseId); + Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + Assert.Null(result.AlbumId); + Assert.NotNull(result.Tracks); + Assert.Equal(request.Tracks!.Count, result.Tracks.Count); + } + + [Fact] + public void ToCommand_WhenMappingTracks_ShouldMapEachTrackToACommandWithTheLibraryIdAndArtistIdAndNullAlbumId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + for (int i = 0; i < request.Tracks!.Count; i++) + { + AddTrackCommand trackCommand = result.Tracks![i]; + Assert.Equal(libraryId.ToString(), trackCommand.LibraryId); + Assert.Equal(artistId.ToString(), trackCommand.ArtistId); + Assert.Null(trackCommand.AlbumId); + Assert.Equal(request.Tracks[i].Path, trackCommand.Path); + Assert.Equal(request.Tracks[i].Metadata, trackCommand.Metadata); + Assert.Equal(request.Tracks[i].TrackNumber, trackCommand.TrackNumber); + } + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls() + { + // Arrange + AddAlbumRequest request = _addAlbumRequestFixture.Create( + includeMediaFormat: false, + includeBarcode: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + includeTracks: false); + + // Act + AddAlbumCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.NotNull(result.Metadata); + Assert.Null(result.MediaFormat); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumber); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.Tracks); + } + + [Fact] + public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds() + { + // Arrange + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + } + + [Fact] + public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + List requests = _addAlbumRequestFixture.CreateMany(3); + + // Act + List result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString())]; + + // Assert + Assert.Equal(requests.Count, result.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].Metadata, result[i].Metadata); + Assert.Equal(requests[i].Tracks!.Count, result[i].Tracks!.Count); + Assert.Equal(libraryId.ToString(), result[i].LibraryId); + Assert.Equal(artistId.ToString(), result[i].ArtistId); + } + } +} 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 new file mode 100644 index 00000000..d2d2676a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs @@ -0,0 +1,344 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using System; +using System.Collections.Generic; +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 AlbumEntityMappingTests +{ + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidAlbumEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + Assert.Equal(entity.Id, album.Id.Value); + Assert.Equal(entity.Title, album.Metadata.Title); + Assert.True(album.Metadata.OriginalTitle.HasValue); + Assert.Equal(entity.OriginalTitle, album.Metadata.OriginalTitle.Value); + Assert.True(album.Metadata.Description.HasValue); + Assert.Equal(entity.Description, album.Metadata.Description.Value); + Assert.Equal(entity.OriginalReleaseDate, album.Metadata.ReleaseInfo.OriginalReleaseDate.Value); + Assert.Equal(entity.OriginalReleaseYear, album.Metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.Equal(entity.ReReleaseDate, album.Metadata.ReleaseInfo.ReReleaseDate.Value); + Assert.Equal(entity.ReReleaseYear, album.Metadata.ReleaseInfo.ReReleaseYear.Value); + Assert.Equal(entity.ReleaseCountry, album.Metadata.ReleaseInfo.ReleaseCountry.Value); + Assert.Equal(entity.ReleaseVersion, album.Metadata.ReleaseInfo.ReleaseVersion.Value); + Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), album.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name)); + Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), album.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name)); + Assert.True(album.Metadata.Language.HasValue); + Assert.Equal(entity.LanguageCode!.ToLowerInvariant(), album.Metadata.Language.Value.LanguageCode); + Assert.Equal(entity.LanguageName, album.Metadata.Language.Value.LanguageName); + Assert.Equal(entity.LanguageNativeName, album.Metadata.Language.Value.NativeName.Value); + Assert.True(album.Metadata.OriginalLanguage.HasValue); + 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.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.MusicBrainzReleaseId, album.MusicBrainzReleaseId.Value.Value); + Assert.Equal(entity.MusicBrainzReleaseGroupId, album.MusicBrainzReleaseGroupId.Value.Value); + Assert.Equal(entity.MusicBrainzReleaseArtistId, album.MusicBrainzReleaseArtistId.Value.Value); + Assert.Equal(entity.Contributors.Select(contributor => contributor.MediaContributorId), album.Contributors.Select(contributor => contributor.ContributorId.Value)); + Assert.Equal(entity.Contributors.Select(contributor => contributor.Role), album.Contributors.Select(contributor => contributor.Role)); + Assert.Equal(entity.Ratings.Select(rating => rating.Value), album.Ratings.Select(rating => (decimal?)rating.Value)); + Assert.Equal(entity.Tracks.Select(track => track.Id), album.Tracks.Select(track => track.Id.Value)); + Assert.Equal(entity.CreatedOnUtc, album.CreatedOnUtc); + Assert.Equal(entity.UpdatedOnUtc, album.UpdatedOnUtc.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create( + includeMetadata: false, + includeTracks: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false, + includeBarcode: false, + includeOriginalTitle: false, + includeDescription: false, + includeLanguage: false, + includeOriginalLanguage: false, + includeReleaseType: false, + includeReleaseStatus: false, + includeTotalDiscs: false, + includeMediaFormat: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + Assert.False(album.Metadata.OriginalTitle.HasValue); + Assert.False(album.Metadata.Description.HasValue); + Assert.False(album.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue); + Assert.False(album.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue); + Assert.False(album.Metadata.ReleaseInfo.ReReleaseDate.HasValue); + Assert.False(album.Metadata.ReleaseInfo.ReReleaseYear.HasValue); + Assert.Empty(album.Metadata.Genres); + Assert.Empty(album.Metadata.Tags); + Assert.False(album.Metadata.Language.HasValue); + Assert.False(album.Metadata.OriginalLanguage.HasValue); + Assert.False(album.Metadata.ReleaseType.HasValue); + 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.False(album.MusicBrainzReleaseId.HasValue); + Assert.False(album.MusicBrainzReleaseGroupId.HasValue); + Assert.False(album.MusicBrainzReleaseArtistId.HasValue); + Assert.Empty(album.Contributors); + Assert.Empty(album.Ratings); + Assert.Empty(album.Tracks); + } + + [Fact] + public void ToDomainEntity_WhenReleaseInfoIsInvalid_ShouldReturnError() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create( + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 1999); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(); + entity.Genres = [_genreEntityFixture.Create(name: string.Empty)]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(); + entity.Tags = [_tagEntityFixture.Create(name: " ")]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenBarcodeCannotBeEmpty_ShouldReturnError() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(barcode: string.Empty); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.BarcodeValueCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenBarcodeHasInvalidFormat_ShouldReturnError() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(barcode: "not-a-barcode"); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.InvalidFormatForBarcode, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenRatingIsInvalid_ShouldReturnError() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(); + entity.Ratings = [_audioRatingEntityFixture.Create(value: 6, maxValue: 5)]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTrackIsInvalid_ShouldReturnError() + { + // Arrange + TrackEntity trackEntity = _trackEntityFixture.Create(); + trackEntity.Isrcs = [new TrackIsrcEntity("not-an-isrc")]; + AlbumEntity entity = _albumEntityFixture.Create(tracks: [trackEntity]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError); + } + + [Fact] + public void ToResponse_WhenMappingAlbumEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(); + + // Act + AlbumResponse result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Id, result.Id); + Assert.Equal(entity.ArtistId, result.ArtistId); + Assert.Equal(entity.LibraryId, result.LibraryId); + Assert.Equal(entity.Title, result.Metadata.Title); + Assert.Equal(entity.OriginalTitle, result.Metadata.OriginalTitle); + Assert.Equal(entity.Description, result.Metadata.Description); + Assert.Equal(entity.OriginalReleaseDate, result.Metadata.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(entity.OriginalReleaseYear, result.Metadata.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(entity.ReReleaseDate, result.Metadata.ReleaseInfo.ReReleaseDate); + Assert.Equal(entity.ReReleaseYear, result.Metadata.ReleaseInfo.ReReleaseYear); + Assert.Equal(entity.ReleaseCountry, result.Metadata.ReleaseInfo.ReleaseCountry); + Assert.Equal(entity.ReleaseVersion, result.Metadata.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Metadata.Language); + Assert.Equal(entity.LanguageCode, result.Metadata.Language!.LanguageCode); + Assert.Equal(entity.LanguageName, result.Metadata.Language.LanguageName); + Assert.Equal(entity.LanguageNativeName, result.Metadata.Language.NativeName); + Assert.NotNull(result.Metadata.OriginalLanguage); + Assert.Equal(entity.OriginalLanguageCode, result.Metadata.OriginalLanguage!.LanguageCode); + Assert.Equal(entity.OriginalLanguageName, result.Metadata.OriginalLanguage.LanguageName); + 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.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.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.Tracks.Select(track => track.Id), result.Tracks!.Select(track => track.Id)); + } + + [Fact] + public void ToResponse_WhenLanguageSubpropertiesAreBlank_ShouldMapLanguagesToNull() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(includeLanguage: false, includeOriginalLanguage: false); + + // Act + AlbumResponse result = entity.ToResponse(); + + // Assert + Assert.Null(result.Metadata.Language); + Assert.Null(result.Metadata.OriginalLanguage); + } + + [Fact] + public void ToResponse_WhenMetadataCollectionsAreEmpty_ShouldMapEmptyCollections() + { + // Arrange + AlbumEntity entity = _albumEntityFixture.Create(includeMetadata: false, includeTracks: false); + + // Act + AlbumResponse result = entity.ToResponse(); + + // Assert + Assert.Empty(result.Contributors!); + Assert.Empty(result.Ratings!); + Assert.Empty(result.Tracks!); + Assert.Empty(result.Metadata.Tags!); + Assert.Empty(result.Metadata.Genres!); + } + + [Fact] + public void ToResponses_WhenMappingMultipleAlbumEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _albumEntityFixture.CreateMany(2); + + // Act + IReadOnlyList results = entities.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.Equal(entities[i].Id, results[i].Id); + Assert.Equal(entities[i].Title, results[i].Metadata.Title); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMappingTests.cs new file mode 100644 index 00000000..eb0cc111 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMappingTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System.Collections.Generic; +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 AlbumLiteRowMappingTests +{ + private readonly AlbumLiteRowFixture _albumLiteRowFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingAlbumLiteRow_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AlbumLiteRow readModel = _albumLiteRowFixture.Create(); + + // Act + AlbumLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(readModel.Id, result.Id); + Assert.Equal(readModel.Title, result.Title); + Assert.Equal(readModel.TotalTracks, result.TotalTracks); + } + + [Fact] + public void ToResponses_WhenMappingMultipleAlbumLiteRows_ShouldMapAllCorrectly() + { + // Arrange + List readModels = _albumLiteRowFixture.CreateMany(2); + + // Act + IReadOnlyList results = readModels.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(readModels.Count, results.Count); + Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id)); + Assert.Equal(readModels.Select(readModel => readModel.Title), results.Select(response => response.Title)); + Assert.Equal(readModels.Select(readModel => readModel.TotalTracks), results.Select(response => response.TotalTracks)); + } + + [Fact] + public void ToResponses_WhenMappingPaginatedAlbumLiteRows_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List readModels = _albumLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedReadModels = _paginatedResultDtoFixture.Create( + data: readModels, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedReadModels.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count); + Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedReadModels.PerPage, result.PerPage); + Assert.Equal(paginatedReadModels.Count, result.Count); + Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages); + } +} 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 new file mode 100644 index 00000000..89be22a7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMappingTests.cs @@ -0,0 +1,158 @@ +#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.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +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 AlbumMappingTests +{ + private readonly AlbumFixture _albumFixture = new(); + private readonly TrackFixture _trackFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteAlbum_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Album album = _albumFixture.Create(); + + // Act + AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId); + + // Assert + Assert.NotNull(result); + Assert.Equal(album.Id.Value, result.Id); + Assert.Equal(artistId, result.ArtistId); + Assert.Equal(libraryId, result.LibraryId); + Assert.Equal(album.Metadata.Title, result.Title); + Assert.Equal(album.Metadata.OriginalTitle.HasValue ? album.Metadata.OriginalTitle.Value : null, result.OriginalTitle); + Assert.Equal(album.Metadata.Description.HasValue ? album.Metadata.Description.Value : null, result.Description); + Assert.Equal(album.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? album.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, result.OriginalReleaseDate); + Assert.Equal(album.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? album.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, result.OriginalReleaseYear); + Assert.Equal(album.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? album.Metadata.ReleaseInfo.ReReleaseDate.Value : null, result.ReReleaseDate); + Assert.Equal(album.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? album.Metadata.ReleaseInfo.ReReleaseYear.Value : null, result.ReReleaseYear); + Assert.Equal(album.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? album.Metadata.ReleaseInfo.ReleaseCountry.Value : null, result.ReleaseCountry); + Assert.Equal(album.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? album.Metadata.ReleaseInfo.ReleaseVersion.Value : null, result.ReleaseVersion); + Assert.Equal(album.Metadata.Language.HasValue ? album.Metadata.Language.Value.LanguageCode : null, result.LanguageCode); + Assert.Equal(album.Metadata.Language.HasValue ? album.Metadata.Language.Value.LanguageName : null, result.LanguageName); + Assert.Equal(album.Metadata.Language.HasValue && album.Metadata.Language.Value.NativeName.HasValue ? album.Metadata.Language.Value.NativeName.Value : null, result.LanguageNativeName); + Assert.Equal(album.Metadata.OriginalLanguage.HasValue ? album.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode); + Assert.Equal(album.Metadata.OriginalLanguage.HasValue ? album.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName); + 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.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.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); + Assert.Equal(album.Ratings.ToRepositoryEntities(), result.Ratings); + Assert.Equal(album.CreatedOnUtc, result.CreatedOnUtc); + Assert.Equal(Guid.Empty, result.CreatedBy); + Assert.Null(result.UpdatedOnUtc); + Assert.Null(result.UpdatedBy); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingContributors_ShouldCreateAContributorEntityPerContributor() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Album album = _albumFixture.Create(); + + // Act + AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId); + + // Assert + Assert.Equal(album.Contributors.Count, result.Contributors.Count); + for (int i = 0; i < album.Contributors.Count; i++) + { + MusicMediaContributor contributor = album.Contributors.ElementAt(i); + AlbumContributorEntity contributorEntity = result.Contributors[i]; + Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); + Assert.Equal(contributor.Role, contributorEntity.Role); + Assert.Equal(album.Id.Value, contributorEntity.AlbumId); + Assert.Equal(album.CreatedOnUtc, contributorEntity.CreatedOnUtc); + Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); + Assert.Null(contributorEntity.UpdatedBy); + } + } + + [Fact] + public void ToRepositoryEntity_WhenMappingTracks_ShouldCreateATrackEntityPerTrackBelongingToTheAlbumAndLibrary() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Album album = _albumFixture.Create(tracks: _trackFixture.CreateMany(2)); + + // Act + AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId); + + // Assert + Assert.Equal(2, result.Tracks.Count); + for (int i = 0; i < album.Tracks.Count; i++) + { + Track track = album.Tracks.ElementAt(i); + TrackEntity trackEntity = result.Tracks[i]; + Assert.Equal(track.Id.Value, trackEntity.Id); + Assert.Equal(album.Id.Value, trackEntity.AlbumId); + Assert.Equal(libraryId, trackEntity.LibraryId); + } + } + + [Fact] + public void ToRepositoryEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNulls() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Album album = _albumFixture.Create( + mediaFormat: Optional.None(), + barcode: Optional.None(), + catalogNumber: Optional.None(), + musicBrainzReleaseId: Optional.None(), + musicBrainzReleaseGroupId: Optional.None(), + musicBrainzReleaseArtistId: Optional.None(), + contributors: [], + ratings: [], + tracks: []); + + // Act + AlbumEntity result = album.ToRepositoryEntity(artistId, libraryId); + + // Assert + Assert.Null(result.MediaFormat); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumber); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Empty(result.Contributors); + Assert.Empty(result.Ratings); + Assert.Empty(result.Tracks); + } +} 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 new file mode 100644 index 00000000..a7a609a2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMappingTests.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 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(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(); + + // Act + Result result = dto.ToDomainEntity(); + + // 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); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndDefaults() + { + // 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); + + // Act + Result result = dto.ToDomainEntity(); + + // 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); + } + + [Fact] + public void ToDomainEntity_WhenLanguageIsMissingRequiredSubproperties_ShouldMapLanguageToNone() + { + // Arrange + LanguageInfoDto incompleteLanguage = _languageInfoDtoFixture.Create(includeLanguageCode: false); + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create( + language: incompleteLanguage, + originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false)); + + // 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); + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(releaseInfo: releaseInfo); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + { + // Arrange + AlbumMetadataDto dto = _albumMetadataDtoFixture.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 + AlbumMetadataDto dto = _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: " ")]); + + // Act + Result result = dto.ToDomainEntity(); + + // 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/GetAlbumTracksLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMappingTests.cs new file mode 100644 index 00000000..5e09a595 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMappingTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteRequestMappingTests +{ + private readonly GetAlbumTracksLiteRequestFixture _getAlbumTracksLiteRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteIds_ShouldMapRouteIdsFromArguments() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + + // Act + GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + Assert.Equal("artist-route", result.ArtistId); + Assert.Equal("album-route", result.AlbumId); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetAlbumTracksLiteQuery result = request.ToQuery("library-route", "artist-route", "album-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} 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 new file mode 100644 index 00000000..9b067a3c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMappingTests.cs @@ -0,0 +1,209 @@ +#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.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +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 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 UpdateAlbumCommandMappingTests +{ + private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString()); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(artist, result.Value); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + 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.MusicBrainzReleaseId, updatedAlbum.MusicBrainzReleaseId.Value.Value); + Assert.Equal(command.MusicBrainzReleaseGroupId, updatedAlbum.MusicBrainzReleaseGroupId.Value.Value); + Assert.Equal(command.MusicBrainzReleaseArtistId, updatedAlbum.MusicBrainzReleaseArtistId.Value.Value); + Assert.Equal(command.Contributors!.Count, updatedAlbum.Contributors.Count); + Assert.Equal(command.Ratings!.Count, updatedAlbum.Ratings.Count); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNones() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + includeMediaFormat: false, + includeBarcode: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + contributors: [], + ratings: []); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Equal(command.Metadata!.Title, updatedAlbum.Metadata.Title); + Assert.False(updatedAlbum.MediaFormat.HasValue); + Assert.False(updatedAlbum.Barcode.HasValue); + Assert.False(updatedAlbum.CatalogNumber.HasValue); + Assert.False(updatedAlbum.MusicBrainzReleaseId.HasValue); + Assert.False(updatedAlbum.MusicBrainzReleaseGroupId.HasValue); + Assert.False(updatedAlbum.MusicBrainzReleaseArtistId.HasValue); + Assert.Empty(updatedAlbum.Contributors); + Assert.Empty(updatedAlbum.Ratings); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); + } + + [Fact] + public void ToDomainEntity_WhenBarcodeCannotBeEmpty_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + barcode: string.Empty); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.BarcodeValueCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenBarcodeHasInvalidFormat_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + barcode: "not-a-barcode"); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.InvalidFormatForBarcode, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid _) = CreateDomainArtist(libraryId); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: Guid.NewGuid().ToString()); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + /// + /// Creates a domain artist that owns a single album belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The created domain artist, together with the Id of its album. + private (Artist artist, Guid albumId) CreateDomainArtist(Guid libraryId) + { + Guid albumId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, libraryId: libraryId, includeTracks: false); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + Result artistResult = artistEntity.ToDomainEntity(); + return (artistResult.Value, albumId); + } +} 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 new file mode 100644 index 00000000..4219f1cb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMappingTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumRequestMappingTests +{ + private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + + // Act + UpdateAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(albumId.ToString(), result.AlbumId); + 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.MusicBrainzReleaseId, result.MusicBrainzReleaseId); + Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls() + { + // Arrange + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create( + includeMediaFormat: false, + includeBarcode: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false); + + // Act + UpdateAlbumCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.NotNull(result.Metadata); + Assert.Null(result.MediaFormat); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumber); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + } + + [Fact] + public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds() + { + // Arrange + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + + // Act + UpdateAlbumCommand result = request.ToCommand(null, null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + Assert.Null(result.AlbumId); + } +} 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 new file mode 100644 index 00000000..096e1e44 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMappingTests.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +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 System; +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 AddArtistCommandMappingTests +{ + private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistCommand command = _addArtistCommandFixture.Create(); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.Equal(libraryId, artist.LibraryId.Value); + Assert.Equal(command.Name, artist.Name); + Assert.True(artist.Website.HasValue); + Assert.Equal(command.Website, artist.Website.Value); + Assert.True(artist.MusicBrainzArtistId.HasValue); + Assert.Equal(command.MusicBrainzArtistId, artist.MusicBrainzArtistId.Value.Value); + Assert.Equal(command.Contributors!.Count, artist.Contributors.Count); + Assert.Equal(command.Albums!.Count, artist.Albums.Count); + Assert.Equal(command.Albums.Select(album => album.Metadata!.Title), artist.Albums.Select(album => album.Metadata.Title)); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistCommand command = _addArtistCommandFixture.Create( + includeWebsite: false, + includeMusicBrainzArtistId: false, + contributors: []); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.False(artist.Website.HasValue); + Assert.False(artist.MusicBrainzArtistId.HasValue); + Assert.Empty(artist.Contributors); + Assert.NotEmpty(artist.Albums); + } + + [Fact] + public void ToDomainEntity_WhenAlbumCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddAlbumCommand invalidAlbum = _addAlbumCommandFixture.Create( + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [invalidAlbum]); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenArtistNameIsEmpty_ShouldReturnError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenArtistHasNoAlbums_ShouldReturnError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: []); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } +} 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 new file mode 100644 index 00000000..a3d0f649 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMappingTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +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 AddArtistRequestMappingTests +{ + private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + + // Act + AddArtistCommand result = request.ToCommand(libraryId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(request.Name, result.Name); + Assert.Equal(request.Website, result.Website); + Assert.Equal(request.MusicBrainzArtistId, result.MusicBrainzArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.NotNull(result.Albums); + Assert.Equal(request.Albums!.Count, result.Albums.Count); + } + + [Fact] + public void ToCommand_WhenMappingAlbums_ShouldMapEachAlbumToACommandWithTheLibraryIdAndNullArtistId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + + // Act + AddArtistCommand result = request.ToCommand(libraryId.ToString()); + + // Assert + for (int i = 0; i < request.Albums!.Count; i++) + { + Assert.Equal(libraryId.ToString(), result.Albums![i].LibraryId); + Assert.Null(result.Albums[i].ArtistId); + 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].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); + Assert.Equal(request.Albums[i].Contributors, result.Albums[i].Contributors); + Assert.Equal(request.Albums[i].Ratings, result.Albums[i].Ratings); + Assert.Null(result.Albums[i].AlbumId); + } + } + + [Fact] + public void ToCommand_WhenAlbumsAreMissing_ShouldMapNullAlbums() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(includeAlbums: false); + + // Act + AddArtistCommand result = request.ToCommand(Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Albums); + } + + [Fact] + public void ToCommand_WhenRouteIdIsNull_ShouldMapNullRouteId() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + + // Act + AddArtistCommand result = request.ToCommand(null); + + // Assert + Assert.Null(result.LibraryId); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapNulls() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create( + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeAlbums: false); + + // Act + AddArtistCommand result = request.ToCommand(Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Null(result.Albums); + } +} 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 new file mode 100644 index 00000000..96fe6768 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMappingTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; +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 ArtistEntityMappingTests +{ + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidArtistEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.Equal(entity.Id, artist.Id.Value); + Assert.Equal(entity.LibraryId, artist.LibraryId.Value); + Assert.Equal(entity.Name, artist.Name); + Assert.True(artist.Website.HasValue); + Assert.Equal(entity.Website, artist.Website.Value); + Assert.True(artist.MusicBrainzArtistId.HasValue); + Assert.Equal(entity.MusicBrainzArtistId, artist.MusicBrainzArtistId.Value.Value); + Assert.Equal(entity.Contributors.Select(contributor => contributor.MediaContributorId), artist.Contributors.Select(contributor => contributor.ContributorId.Value)); + Assert.Equal(entity.Contributors.Select(contributor => contributor.Role), artist.Contributors.Select(contributor => contributor.Role)); + Assert.Equal(entity.Albums.Count, artist.Albums.Count); + Assert.Equal(entity.Albums.Select(album => album.Id), artist.Albums.Select(album => album.Id.Value)); + Assert.Equal(entity.Albums.Select(album => album.Title), artist.Albums.Select(album => album.Metadata.Title)); + Assert.Equal(entity.CreatedOnUtc, artist.CreatedOnUtc); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.Equal(entity.UpdatedOnUtc, artist.UpdatedOnUtc.Value); + } + + [Fact] + public void ToDomainEntity_WhenAlbumCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity invalidAlbum = _albumEntityFixture.Create( + libraryId: libraryId, + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 1999); + ArtistEntity entity = _artistEntityFixture.Create(libraryId: libraryId, albums: [invalidAlbum]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create( + includeMetadata: false, + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeContributors: false); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.False(artist.Website.HasValue); + Assert.False(artist.MusicBrainzArtistId.HasValue); + Assert.Empty(artist.Contributors); + Assert.Single(artist.Albums); + } + + [Fact] + public void ToResponse_WhenMappingArtistEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create(); + + // Act + ArtistResponse result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Id, result.Id); + Assert.Equal(entity.LibraryId, result.LibraryId); + Assert.Equal(entity.Name, result.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.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)); + Assert.Equal(entity.CreatedOnUtc, result.CreatedOnUtc); + Assert.Equal(entity.UpdatedOnUtc, result.UpdatedOnUtc); + } + + [Fact] + public void ToResponse_WhenOptionalPropertiesAreMissing_ShouldMapNullsAndEmptyCollections() + { + // Arrange + ArtistEntity entity = _artistEntityFixture.Create( + includeMetadata: false, + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeContributors: false); + + // Act + ArtistResponse result = entity.ToResponse(); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Empty(result.Contributors!); + Assert.Single(result.Albums!); + } + + [Fact] + public void ToResponses_WhenMappingMultipleArtistEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _artistEntityFixture.CreateMany(2); + + // Act + IReadOnlyList results = entities.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.Equal(entities[i].Id, results[i].Id); + Assert.Equal(entities[i].Name, results[i].Name); + } + } + + [Fact] + public void ToResponses_WhenMappingPaginatedArtistEntities_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List entities = _artistEntityFixture.CreateMany(2); + PaginatedResultDto paginatedEntities = _paginatedResultDtoFixture.Create( + data: entities, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedEntities.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedEntities.Data.Count, result.Data.Count); + Assert.Equal(paginatedEntities.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedEntities.PerPage, result.PerPage); + Assert.Equal(paginatedEntities.Count, result.Count); + Assert.Equal(paginatedEntities.NumberOfPages, result.NumberOfPages); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMappingTests.cs new file mode 100644 index 00000000..e630aa00 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMappingTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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 ArtistLiteRowMappingTests +{ + private readonly ArtistLiteRowFixture _artistLiteRowFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingArtistLiteRow_ShouldMapAllPropertiesCorrectly() + { + // Arrange + ArtistLiteRow readModel = _artistLiteRowFixture.Create(); + + // Act + ArtistLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(readModel.Id, result.Id); + Assert.Equal(readModel.Name, result.Name); + } + + [Fact] + public void ToResponses_WhenMappingMultipleArtistLiteRows_ShouldMapAllCorrectly() + { + // Arrange + List readModels = _artistLiteRowFixture.CreateMany(2); + + // Act + IReadOnlyList results = readModels.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(readModels.Count, results.Count); + Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id)); + Assert.Equal(readModels.Select(readModel => readModel.Name), results.Select(response => response.Name)); + } + + [Fact] + public void ToResponses_WhenMappingPaginatedArtistLiteRows_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List readModels = _artistLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedReadModels = _paginatedResultDtoFixture.Create( + data: readModels, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedReadModels.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count); + Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedReadModels.PerPage, result.PerPage); + Assert.Equal(paginatedReadModels.Count, result.Count); + Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages); + } +} 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 new file mode 100644 index 00000000..04bab90f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMappingTests.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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; +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.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 ArtistMappingTests +{ + private readonly ArtistFixture _artistFixture = new(); + private readonly AlbumFixture _albumFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteArtist_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Artist artist = _artistFixture.Create(); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(artist.Id.Value, result.Id); + Assert.Equal(artist.LibraryId.Value, result.LibraryId); + Assert.Equal(artist.Name, result.Name); + Assert.Equal(artist.Website.Value, result.Website); + Assert.Equal(artist.MusicBrainzArtistId.Value.Value, result.MusicBrainzArtistId); + Assert.Equal(artist.CreatedOnUtc, result.CreatedOnUtc); + Assert.Equal(Guid.Empty, result.CreatedBy); + Assert.Null(result.UpdatedOnUtc); + Assert.Null(result.UpdatedBy); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingContributors_ShouldCreateAContributorEntityPerContributor() + { + // Arrange + Artist artist = _artistFixture.Create(); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(artist.Contributors.Count, result.Contributors.Count); + for (int i = 0; i < artist.Contributors.Count; i++) + { + MusicMediaContributor contributor = artist.Contributors.ElementAt(i); + ArtistContributorEntity contributorEntity = result.Contributors[i]; + Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); + Assert.Equal(contributor.Role, contributorEntity.Role); + Assert.Equal(artist.Id.Value, contributorEntity.ArtistId); + Assert.Equal(artist.CreatedOnUtc, contributorEntity.CreatedOnUtc); + Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); + Assert.Null(contributorEntity.UpdatedBy); + } + } + + [Fact] + public void ToRepositoryEntity_WhenMappingAlbums_ShouldCreateAnAlbumEntityPerAlbum() + { + // Arrange + Artist artist = _artistFixture.Create(); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(artist.Albums.Count, result.Albums.Count); + for (int i = 0; i < artist.Albums.Count; i++) + { + Album album = artist.Albums.ElementAt(i); + AlbumEntity albumEntity = result.Albums[i]; + Assert.Equal(album.Id.Value, albumEntity.Id); + Assert.Equal(artist.Id.Value, albumEntity.ArtistId); + Assert.Equal(artist.LibraryId.Value, albumEntity.LibraryId); + Assert.Equal(album.Metadata.Title, albumEntity.Title); + } + } + + [Fact] + public void ToRepositoryEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNulls() + { + // Arrange + Album album = _albumFixture.Create( + mediaFormat: Optional.None(), + barcode: Optional.None(), + catalogNumber: Optional.None(), + musicBrainzReleaseId: Optional.None(), + musicBrainzReleaseGroupId: Optional.None(), + musicBrainzReleaseArtistId: Optional.None()); + Artist artist = _artistFixture.Create( + website: Optional.None(), + musicBrainzArtistId: Optional.None(), + contributors: [], + albums: [album]); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Empty(result.Contributors); + Assert.Single(result.Albums); + Assert.Null(result.Albums[0].MediaFormat); + Assert.Null(result.Albums[0].Barcode); + Assert.Null(result.Albums[0].CatalogNumber); + Assert.Null(result.Albums[0].MusicBrainzReleaseId); + Assert.Null(result.Albums[0].MusicBrainzReleaseGroupId); + Assert.Null(result.Albums[0].MusicBrainzReleaseArtistId); + } + + [Fact] + public void ToRepositoryEntity_WhenWebsiteIsProvided_ShouldMapIt() + { + // Arrange + string website = "https://www.queenonline.com"; + Artist artist = _artistFixture.Create(website: Optional.Some(website)); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(website, result.Website); + } + + [Fact] + public void ToRepositoryEntity_WhenMusicBrainzArtistIdIsProvided_ShouldMapIt() + { + // Arrange + MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create(); + Artist artist = _artistFixture.Create(musicBrainzArtistId: Optional.Some(musicBrainzArtistId)); + + // Act + ArtistEntity result = artist.ToRepositoryEntity(); + + // Assert + Assert.Equal(musicBrainzArtistId.Value, result.MusicBrainzArtistId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMappingTests.cs new file mode 100644 index 00000000..1e22eff7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMappingTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteRequestMappingTests +{ + private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteIds_ShouldMapRouteIdsFromArguments() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + Assert.Equal("artist-route", result.ArtistId); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetArtistAlbumsLiteQuery result = request.ToQuery("library-route", "artist-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMappingTests.cs new file mode 100644 index 00000000..9f8c28df --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMappingTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteRequestMappingTests +{ + private readonly GetArtistsLiteRequestFixture _getArtistsLiteRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteId_ShouldMapRouteIdFromArgument() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + } + + [Fact] + public void ToQuery_WhenSearchTermIsProvided_ShouldMapIt() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(searchTerm: "queen"); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("queen", result.SearchTerm); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetArtistsLiteQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMappingTests.cs new file mode 100644 index 00000000..9809bb01 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMappingTests.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsRequestMappingTests +{ + private readonly GetArtistsRequestFixture _getArtistsRequestFixture = new(); + + [Fact] + public void ToQuery_WhenCalledWithRouteId_ShouldMapRouteIdFromArgument() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + } + + [Fact] + public void ToQuery_WhenSearchTermIsProvided_ShouldMapIt() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(searchTerm: "queen"); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Equal("queen", result.SearchTerm); + } + + [Fact] + public void ToQuery_WhenNoPaginationValuesAreProvided_ShouldMapNullPaginationData() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.Null(result.PaginationData); + } + + [Fact] + public void ToQuery_WhenOnlyCurrentPageIsProvided_ShouldDefaultPerPageToTwoHundred() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(currentPage: 3, includePerPage: false); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(3, result.PaginationData.CurrentPage); + Assert.Equal(200, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenOnlyPerPageIsProvided_ShouldDefaultCurrentPageToOne() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(perPage: 50, includeCurrentPage: false); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(1, result.PaginationData.CurrentPage); + Assert.Equal(50, result.PaginationData.PerPage); + } + + [Fact] + public void ToQuery_WhenBothPaginationValuesAreProvided_ShouldMapThem() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(currentPage: 2, perPage: 25); + + // Act + GetArtistsQuery result = request.ToQuery("library-route"); + + // Assert + Assert.NotNull(result.PaginationData); + Assert.Equal(2, result.PaginationData.CurrentPage); + Assert.Equal(25, result.PaginationData.PerPage); + } +} 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 new file mode 100644 index 00000000..9382e008 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistAlbumRequestMappingTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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 UpdateArtistAlbumRequestMappingTests +{ + private readonly UpdateArtistAlbumRequestFixture _updateArtistAlbumRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + 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.MusicBrainzReleaseId, result.MusicBrainzReleaseId); + Assert.Equal(request.MusicBrainzReleaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(request.MusicBrainzReleaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + Assert.Equal(request.AlbumId, result.AlbumId); + Assert.NotNull(result.Tracks); + Assert.Equal(request.Tracks!.Count, result.Tracks.Count); + } + + [Fact] + public void ToCommand_WhenMappingTracks_ShouldMapEachTrackToACommandWithTheLibraryIdAndArtistIdAndNullAlbumId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + for (int i = 0; i < request.Tracks!.Count; i++) + { + AddTrackCommand trackCommand = result.Tracks![i]; + Assert.Equal(libraryId.ToString(), trackCommand.LibraryId); + Assert.Equal(artistId.ToString(), trackCommand.ArtistId); + Assert.Null(trackCommand.AlbumId); + Assert.Equal(request.Tracks[i].TrackId, trackCommand.TrackId); + Assert.Equal(request.Tracks[i].Path, trackCommand.Path); + Assert.Equal(request.Tracks[i].Metadata, trackCommand.Metadata); + Assert.Equal(request.Tracks[i].TrackNumber, trackCommand.TrackNumber); + } + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create( + includeAlbumId: false, + includeMediaFormat: false, + includeBarcode: false, + includeCatalogNumber: false, + includeMusicBrainzReleaseId: false, + includeMusicBrainzReleaseGroupId: false, + includeMusicBrainzReleaseArtistId: false, + includeTracks: false); + + // Act + AddAlbumCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result.Metadata); + Assert.Null(result.AlbumId); + Assert.Null(result.MediaFormat); + Assert.Null(result.Barcode); + Assert.Null(result.CatalogNumber); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Null(result.Tracks); + } + + [Fact] + public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds() + { + // Arrange + UpdateArtistAlbumRequest request = _updateArtistAlbumRequestFixture.Create(); + + // Act + AddAlbumCommand result = request.ToCommand(null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + } + + [Fact] + public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + List requests = _updateArtistAlbumRequestFixture.CreateMany(3); + + // Act + List result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString())]; + + // Assert + Assert.Equal(requests.Count, result.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].Metadata, result[i].Metadata); + Assert.Equal(requests[i].AlbumId, result[i].AlbumId); + Assert.Equal(libraryId.ToString(), result[i].LibraryId); + Assert.Equal(artistId.ToString(), result[i].ArtistId); + } + } +} 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 new file mode 100644 index 00000000..907a816d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMappingTests.cs @@ -0,0 +1,274 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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.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 System; +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 UpdateArtistCommandMappingTests +{ + private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + 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"; + AddTrackCommand trackCommand = _addTrackCommandFixture.Create(trackId: trackId, path: updatedPath, trackNumber: 7); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(artist, result.Value); + Assert.Equal(command.Name, result.Value.Name); + Assert.True(result.Value.Website.HasValue); + Assert.Equal(command.Website, result.Value.Website.Value); + Assert.True(result.Value.MusicBrainzArtistId.HasValue); + Assert.Equal(command.MusicBrainzArtistId, result.Value.MusicBrainzArtistId.Value.Value); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Equal(albumCommand.Metadata!.Title, updatedAlbum.Metadata.Title); + Track updatedTrack = updatedAlbum.Tracks.First(track => track.Id.Value == trackId); + Assert.Equal(updatedPath, updatedTrack.Path); + Assert.Equal(7, updatedTrack.TrackNumber); + Assert.True(updatedTrack.DiscNumber.HasValue); + Assert.Equal(trackCommand.DiscNumber, updatedTrack.DiscNumber.Value); + Assert.Equal(trackCommand.Moods!.Count, updatedTrack.Moods.Count); + Assert.Equal(trackCommand.Isrcs!.Count, updatedTrack.Isrcs.Count); + Assert.Equal(trackCommand.Contributors!.Count, updatedTrack.Contributors.Count); + Assert.Equal(trackCommand.Ratings!.Count, updatedTrack.Ratings.Count); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNones() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddTrackCommand trackCommand = _addTrackCommandFixture.Create( + trackId: trackId, + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false, + includeMoods: false, + includeIsrcs: false, + contributors: [], + ratings: []); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [trackCommand]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + includeWebsite: false, + includeMusicBrainzArtistId: false, + contributors: [], + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Website.HasValue); + Assert.False(result.Value.MusicBrainzArtistId.HasValue); + Assert.Empty(result.Value.Contributors); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + Assert.False(updatedTrack.DiscNumber.HasValue); + Assert.False(updatedTrack.Script.HasValue); + Assert.False(updatedTrack.Key.HasValue); + Assert.False(updatedTrack.Bpm.HasValue); + Assert.False(updatedTrack.Work.HasValue); + Assert.Empty(updatedTrack.Moods); + Assert.Empty(updatedTrack.Isrcs); + Assert.Empty(updatedTrack.Contributors); + Assert.Empty(updatedTrack.Ratings); + } + + [Fact] + public void ToDomainEntity_WhenArtistNameIsEmpty_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: []); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + name: string.Empty, + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenAlbumCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand invalidAlbum = _addAlbumCommandFixture.Create( + albumId: albumId, + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [invalidAlbum]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenAllAlbumsAreRemoved_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: []); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenAlbumIsNew_ShouldAddItAndRemoveTheStaleOne() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand newAlbum = _addAlbumCommandFixture.Create(); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [newAlbum]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value.Albums); + Assert.DoesNotContain(result.Value.Albums, album => album.Id.Value == albumId); + } + + [Fact] + public void ToDomainEntity_WhenTrackIsNew_ShouldAddItToTheExistingAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + Guid newTrackId = Guid.NewGuid(); + AddTrackCommand existingTrack = _addTrackCommandFixture.Create(trackId: trackId); + AddTrackCommand newTrack = _addTrackCommandFixture.Create(trackId: newTrackId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: [existingTrack, newTrack]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Equal(2, updatedAlbum.Tracks.Count); + Assert.Contains(updatedAlbum.Tracks, track => track.Id.Value == newTrackId); + Assert.Contains(updatedAlbum.Tracks, track => track.Id.Value == trackId); + } + + [Fact] + public void ToDomainEntity_WhenTrackIsStale_ShouldRemoveItFromTheExistingAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + AddAlbumCommand albumCommand = _addAlbumCommandFixture.Create(albumId: albumId, tracks: []); + UpdateArtistCommand command = _updateArtistCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albums: [albumCommand]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Album updatedAlbum = result.Value.Albums.First(album => album.Id.Value == albumId); + Assert.Empty(updatedAlbum.Tracks); + } + + /// + /// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The created domain artist, together with the Ids of its album and track. + private (Artist artist, Guid albumId, Guid trackId) CreateDomainArtist(Guid libraryId) + { + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + Result artistResult = artistEntity.ToDomainEntity(); + return (artistResult.Value, albumId, trackId); + } +} 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 new file mode 100644 index 00000000..c0409b09 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMappingTests.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistRequestMappingTests +{ + private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + UpdateArtistCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(request.Name, result.Name); + Assert.Equal(request.Website, result.Website); + Assert.Equal(request.MusicBrainzArtistId, result.MusicBrainzArtistId); + Assert.Equal(request.Contributors, result.Contributors); + Assert.NotNull(result.Albums); + Assert.Equal(request.Albums!.Count, result.Albums.Count); + } + + [Fact] + public void ToCommand_WhenMappingAlbums_ShouldMapEachAlbumToACommandWithTheLibraryIdAndArtistId() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + UpdateArtistCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString()); + + // Assert + for (int i = 0; i < request.Albums!.Count; i++) + { + Assert.Equal(libraryId.ToString(), result.Albums![i].LibraryId); + Assert.Equal(artistId.ToString(), result.Albums[i].ArtistId); + Assert.Equal(request.Albums[i].AlbumId, result.Albums[i].AlbumId); + Assert.Equal(request.Albums[i].Metadata, result.Albums[i].Metadata); + } + } + + [Fact] + public void ToCommand_WhenAlbumsAreMissing_ShouldMapNullAlbums() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(includeAlbums: false); + + // Act + UpdateArtistCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Albums); + } + + [Fact] + public void ToCommand_WhenRouteIdsAreNull_ShouldMapNullRouteIds() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + + // Act + UpdateArtistCommand result = request.ToCommand(null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapNulls() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create( + includeWebsite: false, + includeMusicBrainzArtistId: false, + includeAlbums: false); + + // Act + UpdateArtistCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Null(result.Albums); + } +} 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 new file mode 100644 index 00000000..8b71261a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistTrackRequestMappingTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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 UpdateArtistTrackRequestMappingTests +{ + private readonly UpdateArtistTrackRequestFixture _updateArtistTrackRequestFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create(); + + // Act + AddTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(albumId.ToString(), result.AlbumId); + Assert.Equal(request.Path, result.Path); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Equal(request.TrackNumber, result.TrackNumber); + Assert.Equal(request.DiscNumber, result.DiscNumber); + Assert.Equal(request.Script, result.Script); + Assert.Equal(request.Key, result.Key); + Assert.Equal(request.Bpm, result.Bpm); + 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); + Assert.Equal(request.Ratings, result.Ratings); + Assert.Equal(request.TrackId, result.TrackId); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls() + { + // Arrange + UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create( + path: "/music/queen/bohemian-rhapsody.flac", + metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"), + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false, + includeMoods: false, + includeIsrcs: false, + includeTrackId: false); + + // Act + AddTrackCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal("/music/queen/bohemian-rhapsody.flac", result.Path); + Assert.Equal("Love of My Life", result.Metadata!.Title); + Assert.Null(result.DiscNumber); + Assert.Null(result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + 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); + } + + [Fact] + public void ToCommand_WhenRouteIdentifiersAreNull_ShouldMapNullRouteIdentifiers() + { + // Arrange + UpdateArtistTrackRequest request = _updateArtistTrackRequestFixture.Create(); + + // Act + AddTrackCommand result = request.ToCommand(null, null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + Assert.Null(result.AlbumId); + } + + [Fact] + public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + List requests = _updateArtistTrackRequestFixture.CreateMany(3); + + // Act + List result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString(), albumId.ToString())]; + + // Assert + Assert.Equal(requests.Count, result.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].Path, result[i].Path); + Assert.Equal(requests[i].TrackNumber, result[i].TrackNumber); + Assert.Equal(requests[i].TrackId, result[i].TrackId); + Assert.Equal(libraryId.ToString(), result[i].LibraryId); + Assert.Equal(artistId.ToString(), result[i].ArtistId); + Assert.Equal(albumId.ToString(), result[i].AlbumId); + } + } +} 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 new file mode 100644 index 00000000..b77ec6ab --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMappingTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingDtoMappingTests +{ + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteAudioRatingDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AudioRatingDto dto = _audioRatingDtoFixture.Create(); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(dto.Value, result.Value.Value); + Assert.Equal(dto.MaxValue, result.Value.MaxValue); + Assert.True(result.Value.Source.HasValue); + Assert.Equal(dto.Source, result.Value.Source.Value); + Assert.True(result.Value.VoteCount.HasValue); + Assert.Equal(dto.VoteCount, result.Value.VoteCount.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNones() + { + // Arrange + AudioRatingDto dto = _audioRatingDtoFixture.Create(includeSource: false, includeVoteCount: false); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dto.Value, result.Value.Value); + Assert.Equal(dto.MaxValue, result.Value.MaxValue); + Assert.False(result.Value.Source.HasValue); + Assert.False(result.Value.VoteCount.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenValueIsGreaterThanMaxValue_ShouldReturnError() + { + // Arrange + AudioRatingDto dto = _audioRatingDtoFixture.Create(value: 10, maxValue: 5); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidAudioRatingDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = _audioRatingDtoFixture.CreateMany(2); + + // Act + List> results = [.. dtos.ToDomainEntities()]; + + // Assert + Assert.Equal(dtos.Count, results.Count); + for (int i = 0; i < dtos.Count; i++) + { + Assert.False(results[i].IsFailure); + Assert.Equal(dtos[i].Value, results[i].Value.Value); + Assert.Equal(dtos[i].MaxValue, results[i].Value.MaxValue); + } + } + + [Fact] + public void ToDomainEntities_WhenMappingMixedValidAndInvalidAudioRatingDtos_ShouldReturnMixedResults() + { + // Arrange + List dtos = + [ + _audioRatingDtoFixture.Create(value: 4, maxValue: 5), + _audioRatingDtoFixture.Create(value: 10, maxValue: 5), + _audioRatingDtoFixture.Create(value: 3, maxValue: 5) + ]; + + // Act + List> results = [.. dtos.ToDomainEntities()]; + + // Assert + Assert.Equal(dtos.Count, results.Count); + Assert.False(results[0].IsFailure); + Assert.True(results[1].IsFailure); + Assert.False(results[2].IsFailure); + } +} 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 new file mode 100644 index 00000000..9f1ac27b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMappingTests.cs @@ -0,0 +1,167 @@ +#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; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingEntityMappingTests +{ + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidAudioRatingEntity_ShouldMapCorrectly() + { + // Arrange + AudioRatingEntity entity = _audioRatingEntityFixture.Create(); + + // Act + AudioRatingDto result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Value, result.Value); + Assert.Equal(entity.MaxValue, result.MaxValue); + Assert.Equal(entity.Source, result.Source); + Assert.Equal(entity.VoteCount, result.VoteCount); + } + + [Fact] + public void ToResponse_WhenMappingAudioRatingEntityWithNulls_ShouldMapToDefaults() + { + // Arrange + AudioRatingEntity entity = _audioRatingEntityFixture.Create(includeValue: false, includeMaxValue: false, includeSource: false, includeVoteCount: false); + + // Act + AudioRatingDto result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(0, result.Value); + Assert.Equal(0, result.MaxValue); + Assert.Null(result.Source); + Assert.Null(result.VoteCount); + } + + [Fact] + public void ToResponses_WhenMappingMultipleAudioRatingEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _audioRatingEntityFixture.CreateMany(2); + + // Act + List results = [.. entities.ToResponses()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.Equal(entities[i].Value, results[i].Value); + Assert.Equal(entities[i].MaxValue, results[i].MaxValue); + } + } + + [Fact] + public void ToDomainEntity_WhenMappingValidAudioRatingEntity_ShouldMapCorrectly() + { + // Arrange + AudioRatingEntity entity = _audioRatingEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(entity.Value, result.Value.Value); + Assert.Equal(entity.MaxValue, result.Value.MaxValue); + Assert.True(result.Value.Source.HasValue); + Assert.Equal(entity.Source, result.Value.Source.Value); + Assert.True(result.Value.VoteCount.HasValue); + Assert.Equal(entity.VoteCount, result.Value.VoteCount.Value); + } + + [Fact] + public void ToDomainEntity_WhenMappingAudioRatingEntityWithNulls_ShouldMapToDefaults() + { + // Arrange + AudioRatingEntity entity = _audioRatingEntityFixture.Create(includeValue: false, includeMaxValue: false, includeSource: false, includeVoteCount: false); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0, result.Value.Value); + Assert.Equal(0, result.Value.MaxValue); + Assert.False(result.Value.Source.HasValue); + Assert.False(result.Value.VoteCount.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenValueIsGreaterThanMaxValue_ShouldReturnError() + { + // Arrange + AudioRatingEntity entity = _audioRatingEntityFixture.Create(value: 6, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 10); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidAudioRatingEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _audioRatingEntityFixture.CreateMany(2); + + // Act + List> results = [.. entities.ToDomainEntities()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.False(results[i].IsFailure); + Assert.Equal(entities[i].Value, results[i].Value.Value); + Assert.Equal(entities[i].MaxValue, results[i].Value.MaxValue); + } + } + + [Fact] + public void ToDomainEntities_WhenMappingMixedValidAndInvalidAudioRatingEntities_ShouldReturnMixedResults() + { + // Arrange + List entities = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 6, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100) + ]; + + // Act + List> results = [.. entities.ToDomainEntities()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + Assert.False(results[0].IsFailure); + Assert.True(results[1].IsFailure); + Assert.False(results[2].IsFailure); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMappingTests.cs new file mode 100644 index 00000000..92deec10 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMappingTests.cs @@ -0,0 +1,93 @@ +#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.Common.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingMappingTests +{ + private readonly AudioRatingFixture _audioRatingFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteAudioRating_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AudioRating audioRating = _audioRatingFixture.Create(); + + // Act + AudioRatingEntity result = audioRating.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(audioRating.Value, result.Value); + Assert.Equal(audioRating.MaxValue, result.MaxValue); + Assert.Equal(audioRating.Source.Value, result.Source); + Assert.Equal(audioRating.VoteCount.Value, result.VoteCount); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingAudioRatingWithoutSource_ShouldMapCorrectly() + { + // Arrange + AudioRating audioRating = _audioRatingFixture.Create(source: Optional.None()); + + // Act + AudioRatingEntity result = audioRating.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(audioRating.Value, result.Value); + Assert.Equal(audioRating.MaxValue, result.MaxValue); + Assert.Null(result.Source); + Assert.Equal(audioRating.VoteCount.Value, result.VoteCount); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingAudioRatingWithoutVoteCount_ShouldMapCorrectly() + { + // Arrange + AudioRating audioRating = _audioRatingFixture.Create(voteCount: Optional.None()); + + // Act + AudioRatingEntity result = audioRating.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(audioRating.Value, result.Value); + Assert.Equal(audioRating.MaxValue, result.MaxValue); + Assert.Equal(audioRating.Source.Value, result.Source); + Assert.Null(result.VoteCount); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleAudioRatings_ShouldMapAllCorrectly() + { + // Arrange + List audioRatings = _audioRatingFixture.CreateMany(2); + + // Act + List results = [.. audioRatings.ToRepositoryEntities()]; + + // Assert + Assert.Equal(audioRatings.Count, results.Count); + for (int i = 0; i < audioRatings.Count; i++) + { + Assert.Equal(audioRatings[i].Value, results[i].Value); + Assert.Equal(audioRatings[i].MaxValue, results[i].MaxValue); + Assert.Equal(audioRatings[i].Source.Value, results[i].Source); + Assert.Equal(audioRatings[i].VoteCount.Value, results[i].VoteCount); + } + } +} 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 new file mode 100644 index 00000000..067c62d7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMappingTests.cs @@ -0,0 +1,126 @@ +#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; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsrcDtoMappingTests +{ + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidIsrcDto_ShouldMapCorrectly() + { + // Arrange + IsrcDto dto = _isrcDtoFixture.Create(); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(dto.Value!.Trim().ToUpperInvariant(), result.Value.Value); + } + + [Fact] + public void ToDomainEntity_WhenMappingLowercaseIsrcDto_ShouldNormalizeTheValue() + { + // Arrange + IsrcDto dto = _isrcDtoFixture.Create(value: "gbum71029604"); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("GBUM71029604", result.Value.Value); + } + + [Theory] + [InlineData(null)] // missing value + [InlineData("")] // empty value + [InlineData(" ")] // whitespace value + public void ToDomainEntity_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value) + { + // Arrange + IsrcDto dto = _isrcDtoFixture.Create(value: value, includeValue: value is not null); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.IsrcValueCannotBeEmpty, result.FirstError); + } + + [Theory] + [InlineData("invalid")] // not an ISRC at all + [InlineData("GBUM7102960")] // too short + [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) + { + // Arrange + IsrcDto dto = _isrcDtoFixture.Create(value: value); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidIsrcDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = _isrcDtoFixture.CreateMany(2); + + // Act + List> results = [.. dtos.ToDomainEntities()]; + + // Assert + Assert.Equal(dtos.Count, results.Count); + for (int i = 0; i < dtos.Count; i++) + { + Assert.False(results[i].IsFailure); + Assert.Equal(dtos[i].Value!.Trim().ToUpperInvariant(), results[i].Value.Value); + } + } + + [Fact] + public void ToDomainEntities_WhenMappingMixedValidAndInvalidIsrcDtos_ShouldReturnMixedResults() + { + // Arrange + List dtos = + [ + _isrcDtoFixture.Create(value: "GBUM71029604"), + _isrcDtoFixture.Create(value: "invalid"), + _isrcDtoFixture.Create(value: "USRC17607839") + ]; + + // Act + List> results = [.. dtos.ToDomainEntities()]; + + // Assert + Assert.Equal(dtos.Count, results.Count); + Assert.False(results[0].IsFailure); + Assert.True(results[1].IsFailure); + Assert.False(results[2].IsFailure); + } +} 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 new file mode 100644 index 00000000..83acca73 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMappingTests.cs @@ -0,0 +1,136 @@ +#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.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsrcEntityMappingTests +{ + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidTrackIsrcEntity_ShouldMapCorrectly() + { + // Arrange + TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(); + + // Act + IsrcDto result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Value, result.Value); + } + + [Fact] + public void ToResponses_WhenMappingMultipleTrackIsrcEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _trackIsrcEntityFixture.CreateMany(2); + + // Act + List results = [.. entities.ToResponses()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + Assert.Equal(entities[i].Value, results[i].Value); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidTrackIsrcEntity_ShouldMapCorrectly() + { + // Arrange + TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: "GBUM71029604"); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(entity.Value, result.Value.Value); + } + + [Theory] + [InlineData("")] // empty value + [InlineData(" ")] // whitespace value + public void ToDomainEntity_WhenValueIsWhitespace_ShouldReturnError(string value) + { + // Arrange + TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: value); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.IsrcValueCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenValueIsMalformed_ShouldReturnError() + { + // Arrange + TrackIsrcEntity entity = _trackIsrcEntityFixture.Create(value: "not-an-isrc"); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidTrackIsrcEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _trackIsrcEntityFixture.CreateMany(2); + + // Act + List> results = [.. entities.ToDomainEntities()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.False(results[i].IsFailure); + Assert.Equal(entities[i].Value, results[i].Value.Value); + } + } + + [Fact] + public void ToDomainEntities_WhenMappingMixedValidAndInvalidTrackIsrcEntities_ShouldReturnMixedResults() + { + // Arrange + List entities = + [ + _trackIsrcEntityFixture.Create(value: "GBUM71029604"), + _trackIsrcEntityFixture.Create(value: "invalid"), + _trackIsrcEntityFixture.Create(value: "USRC17607839") + ]; + + // Act + List> results = [.. entities.ToDomainEntities()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + Assert.False(results[0].IsFailure); + Assert.True(results[1].IsFailure); + Assert.False(results[2].IsFailure); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMappingTests.cs new file mode 100644 index 00000000..52e14181 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMappingTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +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; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsrcMappingTests +{ + private readonly IsrcFixture _isrcFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingIsrc_ShouldMapCorrectly() + { + // Arrange + Isrc isrc = _isrcFixture.Create(); + + // Act + TrackIsrcEntity result = isrc.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(isrc.Value, result.Value); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleIsrcs_ShouldMapAllCorrectly() + { + // Arrange + List isrcs = _isrcFixture.CreateMany(2); + + // Act + List results = [.. isrcs.ToRepositoryEntities()]; + + // Assert + Assert.Equal(isrcs.Count, results.Count); + for (int i = 0; i < isrcs.Count; i++) + Assert.Equal(isrcs[i].Value, results[i].Value); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingEmptyCollection_ShouldReturnEmptyCollection() + { + // Arrange + List isrcs = []; + + // Act + IEnumerable results = isrcs.ToRepositoryEntities(); + + // Assert + Assert.NotNull(results); + Assert.Empty(results); + } +} 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 new file mode 100644 index 00000000..e0375340 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMappingTests.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MoodDtoMappingTests +{ + private readonly MoodDtoFixture _moodDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidMoodDto_ShouldMapCorrectly() + { + // Arrange + MoodDto dto = _moodDtoFixture.Create(name: " Calm "); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal("Calm", result.Value.Name); + } + + [Theory] + [InlineData(null)] // missing name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void ToDomainEntity_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Arrange + MoodDto dto = _moodDtoFixture.Create(name: name, includeName: name is not null); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.MoodNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidMoodDtos_ShouldMapAllCorrectly() + { + // Arrange + List dtos = _moodDtoFixture.CreateMany(2); + + // Act + List> results = [.. dtos.ToDomainEntities()]; + + // Assert + Assert.Equal(dtos.Count, results.Count); + for (int i = 0; i < dtos.Count; i++) + { + Assert.False(results[i].IsFailure); + Assert.Equal(dtos[i].Name, results[i].Value.Name); + } + } + + [Fact] + public void ToDomainEntities_WhenMappingMixedValidAndInvalidMoodDtos_ShouldReturnMixedResults() + { + // Arrange + List dtos = + [ + _moodDtoFixture.Create(name: "Calm"), + _moodDtoFixture.Create(name: string.Empty, includeName: true), + _moodDtoFixture.Create(name: "Energetic") + ]; + + // Act + List> results = [.. dtos.ToDomainEntities()]; + + // Assert + Assert.Equal(dtos.Count, results.Count); + Assert.False(results[0].IsFailure); + Assert.Equal("Calm", results[0].Value.Name); + Assert.True(results[1].IsFailure); + Assert.False(results[2].IsFailure); + Assert.Equal("Energetic", results[2].Value.Name); + } +} 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 new file mode 100644 index 00000000..b8490ceb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMappingTests.cs @@ -0,0 +1,122 @@ +#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.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MoodEntityMappingTests +{ + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidTrackMoodEntity_ShouldMapCorrectly() + { + // Arrange + TrackMoodEntity entity = _trackMoodEntityFixture.Create(); + + // Act + MoodDto result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Name, result.Name); + } + + [Fact] + public void ToResponses_WhenMappingMultipleTrackMoodEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _trackMoodEntityFixture.CreateMany(2); + + // Act + List results = [.. entities.ToResponses()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + Assert.Equal(entities[i].Name, results[i].Name); + } + + [Fact] + public void ToDomainEntity_WhenMappingValidTrackMoodEntity_ShouldMapCorrectly() + { + // Arrange + TrackMoodEntity entity = _trackMoodEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(entity.Name, result.Value.Name); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void ToDomainEntity_WhenNameIsWhitespace_ShouldReturnError(string name) + { + // Arrange + TrackMoodEntity entity = _trackMoodEntityFixture.Create(name: name); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.MoodNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleValidTrackMoodEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _trackMoodEntityFixture.CreateMany(2); + + // Act + List> results = [.. entities.ToDomainEntities()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.False(results[i].IsFailure); + Assert.Equal(entities[i].Name, results[i].Value.Name); + } + } + + [Fact] + public void ToDomainEntities_WhenMappingMixedValidAndInvalidTrackMoodEntities_ShouldReturnMixedResults() + { + // Arrange + List entities = + [ + _trackMoodEntityFixture.Create(name: "Calm"), + _trackMoodEntityFixture.Create(name: string.Empty), + _trackMoodEntityFixture.Create(name: "Energetic") + ]; + + // Act + List> results = [.. entities.ToDomainEntities()]; + + // Assert + Assert.Equal(entities.Count, results.Count); + Assert.False(results[0].IsFailure); + Assert.True(results[1].IsFailure); + Assert.False(results[2].IsFailure); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMappingTests.cs new file mode 100644 index 00000000..aa71d690 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMappingTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MoodMappingTests +{ + private readonly MoodFixture _moodFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingMood_ShouldMapCorrectly() + { + // Arrange + Mood mood = _moodFixture.Create(); + + // Act + TrackMoodEntity result = mood.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(mood.Name, result.Name); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingMultipleMoods_ShouldMapAllCorrectly() + { + // Arrange + List moods = _moodFixture.CreateMany(2); + + // Act + List results = [.. moods.ToRepositoryEntities()]; + + // Assert + Assert.Equal(moods.Count, results.Count); + for (int i = 0; i < moods.Count; i++) + Assert.Equal(moods[i].Name, results[i].Name); + } + + [Fact] + public void ToRepositoryEntities_WhenMappingEmptyCollection_ShouldReturnEmptyCollection() + { + // Arrange + List moods = []; + + // Act + IEnumerable results = moods.ToRepositoryEntities(); + + // Assert + Assert.NotNull(results); + Assert.Empty(results); + } +} 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 new file mode 100644 index 00000000..edf5f0fd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMappingTests.cs @@ -0,0 +1,163 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary; +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.Entities; +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 AddTrackCommandMappingTests +{ + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(command.Path, result.Value.Path); + Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title); + Assert.Equal(command.TrackNumber!.Value, result.Value.TrackNumber); + Assert.Equal(command.DiscNumber, result.Value.DiscNumber.Value); + 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.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.Moods!.Count, result.Value.Moods.Count); + Assert.Equal(command.Isrcs!.Count, result.Value.Isrcs.Count); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); + Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count); + } + + [Fact] + public void ToDomainEntity_WhenTrackIdIsProvided_ShouldReuseTheProvidedTrackId() + { + // Arrange + Guid trackId = Guid.NewGuid(); + AddTrackCommand command = _addTrackCommandFixture.Create(trackId: trackId); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(trackId, result.Value.Id.Value); + } + + [Fact] + public void ToDomainEntity_WhenTrackIdIsNotProvided_ShouldMintANewTrackId() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotEqual(Guid.Empty, result.Value.Id.Value); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenMoodCreationFails_ShouldReturnError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)]); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.MoodNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenIsrcCreationFails_ShouldReturnError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "invalid")]); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Music.IsrcInvalidFormat.Description); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + Result result = command.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); + } + + [Fact] + public void ToDomainEntities_WhenMappingMultipleCommands_ShouldMapEachCommand() + { + // Arrange + List commands = _addTrackCommandFixture.CreateMany(3); + + // Act + List> results = [.. commands.ToDomainEntities()]; + + // Assert + Assert.Equal(commands.Count, results.Count); + Assert.All(results, result => Assert.False(result.IsFailure)); + for (int i = 0; i < commands.Count; i++) + { + Assert.Equal(commands[i].Path, results[i].Value.Path); + Assert.Equal(commands[i].Metadata!.Title, results[i].Value.Metadata.Title); + } + } +} 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 new file mode 100644 index 00000000..3cedb065 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMappingTests.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.Tracks; +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 AddTrackRequestMappingTests +{ + private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddTrackRequest request = _addTrackRequestFixture.Create(); + + // Act + AddTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(albumId.ToString(), result.AlbumId); + Assert.Equal(request.Path, result.Path); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Equal(request.TrackNumber, result.TrackNumber); + Assert.Equal(request.DiscNumber, result.DiscNumber); + Assert.Equal(request.Script, result.Script); + Assert.Equal(request.Key, result.Key); + Assert.Equal(request.Bpm, result.Bpm); + 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); + Assert.Equal(request.Ratings, result.Ratings); + Assert.Null(result.TrackId); + } + + [Fact] + public void ToCommand_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredPropertiesAndNulls() + { + // Arrange + AddTrackRequest request = _addTrackRequestFixture.Create( + path: "/music/queen/bohemian-rhapsody.flac", + metadata: _audioMetadataDtoFixture.Create(title: "Love of My Life"), + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false, + includeMoods: false, + includeIsrcs: false); + + // Act + AddTrackCommand result = request.ToCommand(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal("/music/queen/bohemian-rhapsody.flac", result.Path); + Assert.Equal("Love of My Life", result.Metadata!.Title); + Assert.Null(result.DiscNumber); + Assert.Null(result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + Assert.Null(result.Work); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzTrackId); + Assert.Null(result.MusicBrainzWorkId); + Assert.Null(result.Moods); + Assert.Null(result.Isrcs); + } + + [Fact] + public void ToCommand_WhenRouteIdentifiersAreNull_ShouldMapNullRouteIdentifiers() + { + // Arrange + AddTrackRequest request = _addTrackRequestFixture.Create(); + + // Act + AddTrackCommand result = request.ToCommand(null, null, null); + + // Assert + Assert.Null(result.LibraryId); + Assert.Null(result.ArtistId); + Assert.Null(result.AlbumId); + } + + [Fact] + public void ToCommands_WhenMappingMultipleRequests_ShouldMapEachRequest() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + List requests = _addTrackRequestFixture.CreateMany(3); + + // Act + List result = [.. requests.ToCommands(libraryId.ToString(), artistId.ToString(), albumId.ToString())]; + + // Assert + Assert.Equal(requests.Count, result.Count); + for (int i = 0; i < requests.Count; i++) + { + Assert.Equal(requests[i].Path, result[i].Path); + Assert.Equal(requests[i].TrackNumber, result[i].TrackNumber); + Assert.Equal(libraryId.ToString(), result[i].LibraryId); + Assert.Equal(artistId.ToString(), result[i].ArtistId); + Assert.Equal(albumId.ToString(), result[i].AlbumId); + } + } +} 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 new file mode 100644 index 00000000..64490585 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMappingTests.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 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(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + AudioMetadataDto dto = _audioMetadataDtoFixture.Create(); + + // Act + Result result = dto.ToDomainEntity(); + + // 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 + 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); + + // Act + Result result = dto.ToDomainEntity(); + + // 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); + AudioMetadataDto dto = _audioMetadataDtoFixture.Create( + language: incompleteLanguage, + originalLanguage: _languageInfoDtoFixture.Create(includeLanguageName: false)); + + // 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(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + { + // 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); + } +} 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 new file mode 100644 index 00000000..5d90ead0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMappingTests.cs @@ -0,0 +1,275 @@ +#region ========================================================================= USING ===================================================================================== +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.MediaLibrary.AudioLibrary.MusicLibrary; +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.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +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 TrackEntityMappingTests +{ + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidTrackEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Track track = result.Value; + Assert.Equal(entity.Id, track.Id.Value); + Assert.Equal(entity.Path, track.Path); + Assert.Equal(entity.Title, track.Metadata.Title); + Assert.True(track.Metadata.OriginalTitle.HasValue); + Assert.Equal(entity.OriginalTitle, track.Metadata.OriginalTitle.Value); + Assert.True(track.Metadata.Description.HasValue); + Assert.Equal(entity.Description, track.Metadata.Description.Value); + Assert.Equal(entity.OriginalReleaseDate, track.Metadata.ReleaseInfo.OriginalReleaseDate.Value); + Assert.Equal(entity.OriginalReleaseYear, track.Metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.Equal(entity.ReReleaseDate, track.Metadata.ReleaseInfo.ReReleaseDate.Value); + Assert.Equal(entity.ReReleaseYear, track.Metadata.ReleaseInfo.ReReleaseYear.Value); + Assert.Equal(entity.ReleaseCountry, track.Metadata.ReleaseInfo.ReleaseCountry.Value); + Assert.Equal(entity.ReleaseVersion, track.Metadata.ReleaseInfo.ReleaseVersion.Value); + Assert.True(track.Metadata.Language.HasValue); + Assert.Equal(entity.LanguageCode!.ToLowerInvariant(), track.Metadata.Language.Value.LanguageCode); + Assert.Equal(entity.LanguageName, track.Metadata.Language.Value.LanguageName); + Assert.Equal(entity.LanguageNativeName, track.Metadata.Language.Value.NativeName.Value); + Assert.True(track.Metadata.OriginalLanguage.HasValue); + Assert.Equal(entity.OriginalLanguageCode!.ToLowerInvariant(), track.Metadata.OriginalLanguage.Value.LanguageCode); + Assert.Equal(entity.OriginalLanguageName, track.Metadata.OriginalLanguage.Value.LanguageName); + Assert.Equal(entity.OriginalLanguageNativeName, track.Metadata.OriginalLanguage.Value.NativeName.Value); + Assert.Equal(entity.DurationInSeconds, track.Metadata.DurationInSeconds); + Assert.Equal(entity.SampleRate, track.Metadata.SampleRate); + Assert.Equal(entity.Channels, track.Metadata.Channels); + Assert.Equal(entity.BitDepth, track.Metadata.BitDepth.Value); + Assert.Equal(entity.AudioCodec, track.Metadata.AudioCodec.Value); + Assert.Equal(entity.Bitrate, track.Metadata.Bitrate.Value); + Assert.Equal(entity.Genres.Select(genre => genre.Name).OrderBy(name => name), track.Metadata.Genres.Select(genre => genre.Name).OrderBy(name => name)); + Assert.Equal(entity.Tags.Select(tag => tag.Name).OrderBy(name => name), track.Metadata.Tags.Select(tag => tag.Name).OrderBy(name => name)); + Assert.Equal(entity.TrackNumber, track.TrackNumber); + Assert.Equal(entity.DiscNumber, track.DiscNumber.Value); + 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.MusicBrainzRecordingId, track.MusicBrainzRecordingId.Value.Value); + Assert.Equal(entity.MusicBrainzTrackId, track.MusicBrainzTrackId.Value.Value); + Assert.Equal(entity.MusicBrainzWorkId, track.MusicBrainzWorkId.Value.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)); + Assert.Equal(entity.Contributors.Select(contributor => contributor.MediaContributorId), track.Contributors.Select(contributor => contributor.ContributorId.Value)); + Assert.Equal(entity.Contributors.Select(contributor => contributor.Role), track.Contributors.Select(contributor => contributor.Role)); + Assert.Equal(entity.CreatedOnUtc, track.CreatedOnUtc); + Assert.Equal(entity.UpdatedOnUtc, track.UpdatedOnUtc.Value); + } + + [Fact] + public void ToDomainEntity_WhenReleaseDateAndYearDoNotMatch_ShouldReturnError() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create( + originalReleaseDate: new DateOnly(2000, 1, 1), + originalReleaseYear: 1999); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenGenreIsInvalid_ShouldReturnError() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + entity.Genres = [new GenreEntity(string.Empty)]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTagIsInvalid_ShouldReturnError() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + entity.Tags = [new TagEntity(" ")]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenMoodIsInvalid_ShouldReturnError() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + entity.Moods = [new TrackMoodEntity(string.Empty)]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.MoodNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenIsrcIsInvalid_ShouldReturnError() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + entity.Isrcs = [new TrackIsrcEntity("not-an-isrc")]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.IsrcInvalidFormat, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenRatingIsInvalid_ShouldReturnError() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + entity.Ratings = [_audioRatingEntityFixture.Create(value: 6, maxValue: 5, includeSource: false, includeVoteCount: false)]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError); + } + + [Fact] + public void ToResponse_WhenMappingTrackEntity_ShouldMapAllPropertiesCorrectly() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + + // Act + TrackResponse result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Id, result.Id); + Assert.Equal(entity.AlbumId, result.AlbumId); + Assert.Equal(entity.LibraryId, result.LibraryId); + Assert.Equal(entity.Path, result.Path); + Assert.Equal(entity.Title, result.Metadata.Title); + Assert.Equal(entity.OriginalTitle, result.Metadata.OriginalTitle); + Assert.Equal(entity.Description, result.Metadata.Description); + Assert.Equal(entity.OriginalReleaseDate, result.Metadata.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(entity.OriginalReleaseYear, result.Metadata.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(entity.ReReleaseDate, result.Metadata.ReleaseInfo.ReReleaseDate); + Assert.Equal(entity.ReReleaseYear, result.Metadata.ReleaseInfo.ReReleaseYear); + Assert.Equal(entity.ReleaseCountry, result.Metadata.ReleaseInfo.ReleaseCountry); + Assert.Equal(entity.ReleaseVersion, result.Metadata.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Metadata.Language); + Assert.Equal(entity.LanguageCode, result.Metadata.Language!.LanguageCode); + Assert.Equal(entity.LanguageName, result.Metadata.Language.LanguageName); + Assert.Equal(entity.LanguageNativeName, result.Metadata.Language.NativeName); + Assert.NotNull(result.Metadata.OriginalLanguage); + Assert.Equal(entity.OriginalLanguageCode, result.Metadata.OriginalLanguage!.LanguageCode); + Assert.Equal(entity.OriginalLanguageName, result.Metadata.OriginalLanguage.LanguageName); + Assert.Equal(entity.OriginalLanguageNativeName, result.Metadata.OriginalLanguage.NativeName); + Assert.Equal(entity.DurationInSeconds, result.Metadata.DurationInSeconds); + Assert.Equal(entity.SampleRate, result.Metadata.SampleRate); + Assert.Equal(entity.Channels, result.Metadata.Channels); + Assert.Equal(entity.BitDepth, result.Metadata.BitDepth); + Assert.Equal(entity.AudioCodec, result.Metadata.AudioCodec); + Assert.Equal(entity.Bitrate, result.Metadata.Bitrate); + 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.TrackNumber, result.TrackNumber); + Assert.Equal(entity.DiscNumber, result.DiscNumber); + 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.MusicBrainzRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(entity.MusicBrainzTrackId, result.MusicBrainzTrackId); + Assert.Equal(entity.MusicBrainzWorkId, result.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); + } + + [Fact] + public void ToResponse_WhenLanguageSubpropertiesAreBlank_ShouldMapLanguagesToNull() + { + // Arrange + TrackEntity entity = _trackEntityFixture.Create(); + entity.LanguageCode = null; + entity.LanguageName = null; + entity.LanguageNativeName = null; + entity.OriginalLanguageCode = null; + entity.OriginalLanguageName = null; + entity.OriginalLanguageNativeName = null; + + // Act + TrackResponse result = entity.ToResponse(); + + // Assert + Assert.Null(result.Metadata.Language); + Assert.Null(result.Metadata.OriginalLanguage); + } + + [Fact] + public void ToResponses_WhenMappingMultipleTrackEntities_ShouldMapAllCorrectly() + { + // Arrange + List entities = _trackEntityFixture.CreateMany(2); + + // Act + IReadOnlyList results = entities.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(entities.Count, results.Count); + for (int i = 0; i < entities.Count; i++) + { + Assert.Equal(entities[i].Id, results[i].Id); + Assert.Equal(entities[i].Title, results[i].Metadata.Title); + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMappingTests.cs new file mode 100644 index 00000000..b3f06a6f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMappingTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +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 TrackLiteRowMappingTests +{ + private readonly TrackLiteRowFixture _trackLiteRowFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingTrackLiteRow_ShouldMapAllPropertiesCorrectly() + { + // Arrange + TrackLiteRow readModel = _trackLiteRowFixture.Create(); + + // Act + TrackLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(readModel.Id, result.Id); + Assert.Equal(readModel.Title, result.Title); + Assert.Equal(readModel.TrackNumber, result.TrackNumber); + Assert.Equal(readModel.DiscNumber, result.DiscNumber); + } + + [Fact] + public void ToResponse_WhenDiscNumberIsProvided_ShouldMapIt() + { + // Arrange + TrackLiteRow readModel = _trackLiteRowFixture.Create(discNumber: 2); + + // Act + TrackLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.Equal(2, result.DiscNumber); + } + + [Fact] + public void ToResponses_WhenMappingMultipleTrackLiteRows_ShouldMapAllCorrectly() + { + // Arrange + List readModels = _trackLiteRowFixture.CreateMany(2); + + // Act + IReadOnlyList results = readModels.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(readModels.Count, results.Count); + Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id)); + Assert.Equal(readModels.Select(readModel => readModel.TrackNumber), results.Select(response => response.TrackNumber)); + } + + [Fact] + public void ToResponses_WhenMappingPaginatedTrackLiteRows_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List readModels = _trackLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedReadModels = _paginatedResultDtoFixture.Create( + data: readModels, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedReadModels.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count); + Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedReadModels.PerPage, result.PerPage); + Assert.Equal(paginatedReadModels.Count, result.Count); + Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages); + } +} 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 new file mode 100644 index 00000000..f0d25362 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMappingTests.cs @@ -0,0 +1,187 @@ +#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.Common; +using Lumina.Application.Common.Mapping.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.MusicLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +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 TrackMappingTests +{ + private readonly TrackFixture _trackFixture = new(); + private readonly AudioMetadataFixture _audioMetadataFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingCompleteTrack_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Track track = _trackFixture.Create(); + + // Act + TrackEntity result = track.ToRepositoryEntity(albumId, libraryId); + + // Assert + Assert.NotNull(result); + Assert.Equal(track.Id.Value, result.Id); + Assert.Equal(albumId, result.AlbumId); + Assert.Equal(libraryId, result.LibraryId); + Assert.Equal(track.Path, result.Path); + Assert.Equal(track.Metadata.Title, result.Title); + Assert.Equal(track.Metadata.OriginalTitle.HasValue ? track.Metadata.OriginalTitle.Value : null, result.OriginalTitle); + Assert.Equal(track.Metadata.Description.HasValue ? track.Metadata.Description.Value : null, result.Description); + Assert.Equal(track.Metadata.ReleaseInfo.OriginalReleaseDate.HasValue ? track.Metadata.ReleaseInfo.OriginalReleaseDate.Value : null, result.OriginalReleaseDate); + Assert.Equal(track.Metadata.ReleaseInfo.OriginalReleaseYear.HasValue ? track.Metadata.ReleaseInfo.OriginalReleaseYear.Value : null, result.OriginalReleaseYear); + Assert.Equal(track.Metadata.ReleaseInfo.ReReleaseDate.HasValue ? track.Metadata.ReleaseInfo.ReReleaseDate.Value : null, result.ReReleaseDate); + Assert.Equal(track.Metadata.ReleaseInfo.ReReleaseYear.HasValue ? track.Metadata.ReleaseInfo.ReReleaseYear.Value : null, result.ReReleaseYear); + Assert.Equal(track.Metadata.ReleaseInfo.ReleaseCountry.HasValue ? track.Metadata.ReleaseInfo.ReleaseCountry.Value : null, result.ReleaseCountry); + Assert.Equal(track.Metadata.ReleaseInfo.ReleaseVersion.HasValue ? track.Metadata.ReleaseInfo.ReleaseVersion.Value : null, result.ReleaseVersion); + Assert.Equal(track.Metadata.Language.HasValue ? track.Metadata.Language.Value.LanguageCode : null, result.LanguageCode); + Assert.Equal(track.Metadata.Language.HasValue ? track.Metadata.Language.Value.LanguageName : null, result.LanguageName); + Assert.Equal(track.Metadata.Language.HasValue && track.Metadata.Language.Value.NativeName.HasValue ? track.Metadata.Language.Value.NativeName.Value : null, result.LanguageNativeName); + Assert.Equal(track.Metadata.OriginalLanguage.HasValue ? track.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode); + Assert.Equal(track.Metadata.OriginalLanguage.HasValue ? track.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName); + Assert.Equal(track.Metadata.OriginalLanguage.HasValue && track.Metadata.OriginalLanguage.Value.NativeName.HasValue ? track.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName); + // The repository entity stores genres and tags as sets, so duplicate names in the domain collection collapse into a single entry. + Assert.Equal(track.Metadata.Genres.ToRepositoryEntities().Distinct().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name)); + Assert.Equal(track.Metadata.Tags.ToRepositoryEntities().Distinct().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name)); + Assert.Equal(track.Metadata.DurationInSeconds, result.DurationInSeconds); + Assert.Equal(track.Metadata.SampleRate, result.SampleRate); + Assert.Equal(track.Metadata.Channels, result.Channels); + Assert.Equal(track.Metadata.BitDepth.HasValue ? track.Metadata.BitDepth.Value : null, result.BitDepth); + Assert.Equal(track.Metadata.AudioCodec.HasValue ? track.Metadata.AudioCodec.Value : null, result.AudioCodec); + Assert.Equal(track.Metadata.Bitrate.HasValue ? track.Metadata.Bitrate.Value : null, result.Bitrate); + Assert.Equal(track.TrackNumber, result.TrackNumber); + Assert.Equal(track.DiscNumber.HasValue ? track.DiscNumber.Value : null, result.DiscNumber); + 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.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.Moods.ToRepositoryEntities(), result.Moods); + Assert.Equal(track.Isrcs.ToRepositoryEntities(), result.Isrcs); + Assert.Equal(track.Ratings.ToRepositoryEntities(), result.Ratings); + Assert.Equal(track.CreatedOnUtc, result.CreatedOnUtc); + Assert.Equal(Guid.Empty, result.CreatedBy); + Assert.Null(result.UpdatedOnUtc); + Assert.Null(result.UpdatedBy); + } + + [Fact] + public void ToRepositoryEntity_WhenMappingContributors_ShouldCreateAContributorEntityPerContributor() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Track track = _trackFixture.Create(); + + // Act + TrackEntity result = track.ToRepositoryEntity(albumId, libraryId); + + // Assert + Assert.Equal(track.Contributors.Count, result.Contributors.Count); + for (int i = 0; i < track.Contributors.Count; i++) + { + MusicMediaContributor contributor = track.Contributors.ElementAt(i); + TrackContributorEntity contributorEntity = result.Contributors[i]; + Assert.Equal(contributor.ContributorId.Value, contributorEntity.MediaContributorId); + Assert.Equal(contributor.Role, contributorEntity.Role); + Assert.Equal(track.Id.Value, contributorEntity.TrackId); + Assert.Equal(track.CreatedOnUtc, contributorEntity.CreatedOnUtc); + Assert.Equal(Guid.Empty, contributorEntity.CreatedBy); + Assert.Null(contributorEntity.UpdatedOnUtc); + Assert.Null(contributorEntity.UpdatedBy); + } + } + + [Fact] + public void ToRepositoryEntity_WhenOptionalPropertiesAreMissing_ShouldMapTheRequiredValuesAndNulls() + { + // Arrange + Guid albumId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + AudioMetadata metadata = _audioMetadataFixture.Create( + originalTitle: Optional.None(), + description: Optional.None(), + releaseInfo: ReleaseInfo.Create( + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()).Value, + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + Track track = _trackFixture.Create( + metadata: metadata, + discNumber: Optional.None(), + script: Optional.None(), + key: Optional.None(), + bpm: Optional.None(), + work: Optional.None(), + moods: [], + isrcs: [], + musicBrainzRecordingId: Optional.None(), + musicBrainzTrackId: Optional.None(), + musicBrainzWorkId: Optional.None(), + contributors: [], + ratings: []); + + // Act + TrackEntity result = track.ToRepositoryEntity(albumId, libraryId); + + // Assert + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Null(result.OriginalReleaseDate); + Assert.Null(result.OriginalReleaseYear); + Assert.Null(result.ReReleaseDate); + Assert.Null(result.ReReleaseYear); + Assert.Null(result.ReleaseCountry); + Assert.Null(result.ReleaseVersion); + Assert.Null(result.LanguageCode); + Assert.Null(result.LanguageName); + Assert.Null(result.LanguageNativeName); + Assert.Null(result.OriginalLanguageCode); + Assert.Null(result.OriginalLanguageName); + Assert.Null(result.OriginalLanguageNativeName); + Assert.Null(result.BitDepth); + Assert.Null(result.AudioCodec); + Assert.Null(result.Bitrate); + Assert.Null(result.DiscNumber); + Assert.Null(result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + Assert.Null(result.Work); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzTrackId); + Assert.Null(result.MusicBrainzWorkId); + Assert.Empty(result.Moods); + Assert.Empty(result.Isrcs); + Assert.Empty(result.Contributors); + Assert.Empty(result.Ratings); + } +} 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 new file mode 100644 index 00000000..a88c1501 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMappingTests.cs @@ -0,0 +1,259 @@ +#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.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.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.SharedKernel.Common.Enums.MediaContributors; +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 UpdateTrackCommandMappingTests +{ + private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + string updatedPath = "/music/queen/a-night-at-the-opera/02-love-of-my-life.flac"; + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), path: updatedPath); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(artist, result.Value); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + Assert.Equal(updatedPath, updatedTrack.Path); + Assert.Equal(command.Metadata!.Title, updatedTrack.Metadata.Title); + Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber); + Assert.True(updatedTrack.DiscNumber.HasValue); + Assert.Equal(command.DiscNumber, updatedTrack.DiscNumber.Value); + Assert.True(updatedTrack.Script.HasValue); + Assert.Equal(command.Script, updatedTrack.Script.Value); + Assert.True(updatedTrack.Key.HasValue); + Assert.Equal(command.Key, updatedTrack.Key.Value); + 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.MusicBrainzRecordingId, updatedTrack.MusicBrainzRecordingId.Value.Value); + Assert.Equal(command.MusicBrainzTrackId, updatedTrack.MusicBrainzTrackId.Value.Value); + Assert.Equal(command.MusicBrainzWorkId, updatedTrack.MusicBrainzWorkId.Value.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); + Assert.Equal(command.Ratings!.Count, updatedTrack.Ratings.Count); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly() + { + // Arrange + 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: []); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + Assert.Equal(updatedPath, updatedTrack.Path); + Assert.Equal(command.TrackNumber, updatedTrack.TrackNumber); + Assert.False(updatedTrack.DiscNumber.HasValue); + Assert.False(updatedTrack.Script.HasValue); + Assert.False(updatedTrack.Key.HasValue); + Assert.False(updatedTrack.Bpm.HasValue); + 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); + Assert.Empty(updatedTrack.Ratings); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + trackId: trackId.ToString(), + metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenMoodCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), moods: [_moodDtoFixture.Create(name: string.Empty)]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.MoodNameCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenIsrcCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), isrcs: [_isrcDtoFixture.Create(value: string.Empty)]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Music.IsrcValueCannotBeEmpty.Description); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description); + } + + [Fact] + public void ToDomainEntity_WhenTheSameContributorHasDifferentRoles_ShouldKeepBothRoles() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid trackId) = CreateDomainArtist(libraryId); + Guid contributorId = Guid.NewGuid(); + UpdateTrackCommand command = _updateTrackCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artist.Id.Value.ToString(), + albumId: albumId.ToString(), + trackId: trackId.ToString(), + contributors: + [ + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Vocals), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Guitar) + ]); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.False(result.IsFailure); + Track updatedTrack = result.Value.Albums.First(album => album.Id.Value == albumId).Tracks.First(track => track.Id.Value == trackId); + Assert.Equal(2, updatedTrack.Contributors.Count); + Assert.All(updatedTrack.Contributors, contributor => Assert.Equal(contributorId, contributor.ContributorId.Value)); + Assert.Contains(updatedTrack.Contributors, contributor => contributor.Role == MediaContributorRole.Vocals); + Assert.Contains(updatedTrack.Contributors, contributor => contributor.Role == MediaContributorRole.Guitar); + } + + [Fact] + public void ToDomainEntity_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid _, Guid trackId) = CreateDomainArtist(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: Guid.NewGuid().ToString(), trackId: trackId.ToString()); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenTrackIsNotPartOfTheAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (Artist artist, Guid albumId, Guid _) = CreateDomainArtist(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.Value.ToString(), albumId: albumId.ToString(), trackId: Guid.NewGuid().ToString()); + + // Act + Result result = command.ToDomainEntity(artist); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + /// + /// Creates a domain artist that owns a single album, which in turn owns a single track, all belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The created domain artist, together with the Ids of its album and track. + private (Artist artist, Guid albumId, Guid trackId) CreateDomainArtist(Guid libraryId) + { + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AlbumEntity albumEntity = _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]); + ArtistEntity artistEntity = _artistEntityFixture.Create(libraryId: libraryId, albums: [albumEntity]); + Result artistResult = artistEntity.ToDomainEntity(); + return (artistResult.Value, albumId, trackId); + } +} 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 new file mode 100644 index 00000000..22308dc6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMappingTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackRequestMappingTests +{ + private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(albumId.ToString(), result.AlbumId); + Assert.Equal(trackId.ToString(), result.TrackId); + Assert.Equal(request.Path, result.Path); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Equal(request.TrackNumber, result.TrackNumber); + Assert.Equal(request.DiscNumber, result.DiscNumber); + Assert.Equal(request.Script, result.Script); + Assert.Equal(request.Key, result.Key); + Assert.Equal(request.Bpm, result.Bpm); + 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); + Assert.Equal(request.Ratings, result.Ratings); + } + + [Fact] + public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create( + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false, + includeMoods: false, + includeIsrcs: false, + contributors: [], + ratings: []); + + // Act + UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(artistId.ToString(), result.ArtistId); + Assert.Equal(albumId.ToString(), result.AlbumId); + Assert.Equal(trackId.ToString(), result.TrackId); + Assert.NotNull(result.Metadata); + Assert.Equal(request.Metadata, result.Metadata); + Assert.Null(result.DiscNumber); + Assert.Null(result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + 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!); + Assert.Empty(result.Ratings!); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create( + moods: [new("dramatic")], + isrcs: [new("GBUM71029604")], + contributors: [new(Guid.NewGuid(), MediaContributorRole.Vocals)], + ratings: [new(4.5m, 5m, AudioRatingSource.MusicBrainz, 1000)], + includeDiscNumber: false, + includeScript: false, + includeKey: false, + includeBpm: false, + includeWork: false, + includeMusicBrainzRecordingId: false, + includeMusicBrainzTrackId: false, + includeMusicBrainzWorkId: false); + + // Act + UpdateTrackCommand result = request.ToCommand(libraryId.ToString(), artistId.ToString(), albumId.ToString(), trackId.ToString()); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.Moods, result.Moods); + Assert.Equal(request.Isrcs, result.Isrcs); + Assert.Equal(request.Contributors, result.Contributors); + Assert.Equal(request.Ratings, result.Ratings); + } + + [Fact] + public void ToCommand_WhenCalledWithRouteIds_ShouldMapRouteIdsFromArguments() + { + // Arrange + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + + // Act + UpdateTrackCommand result = request.ToCommand("library-route", "artist-route", "album-route", "track-route"); + + // Assert + Assert.Equal("library-route", result.LibraryId); + Assert.Equal("artist-route", result.ArtistId); + Assert.Equal("album-route", result.AlbumId); + Assert.Equal("track-route", result.TrackId); + } +} 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 28e95ff7..0a85aec0 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 @@ -48,9 +48,9 @@ public class LibraryMappingTests Assert.Equal(library.Title, result.Title); Assert.Equal(library.LibraryType, result.LibraryType); Assert.Equal(library.ContentLocations.Select(l => l.Path), result.ContentLocations.Select(l => l.Path)); - Assert.Equal(library.CoverImage, result.CoverImage); + Assert.Equal(library.CoverImage.HasValue ? library.CoverImage.Value : null, result.CoverImage); Assert.Equal(library.CreatedOnUtc, result.CreatedOnUtc); - Assert.Equal(library.UpdatedOnUtc, result.UpdatedOnUtc); + Assert.Equal(library.UpdatedOnUtc.HasValue ? library.UpdatedOnUtc.Value : null, result.UpdatedOnUtc); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); Assert.True(result.CanDownloadMetadataFromWeb); @@ -74,7 +74,7 @@ public class LibraryMappingTests // Assert Assert.NotNull(result); Assert.Empty(result.ContentLocations); - Assert.Equal(library.CoverImage, result.CoverImage); + Assert.Equal(library.CoverImage.HasValue ? library.CoverImage.Value : null, result.CoverImage); } [Theory] @@ -101,7 +101,7 @@ public class LibraryMappingTests // Assert Assert.NotNull(result); Assert.Equal(libraryType, result.LibraryType); - Assert.Equal(library.CoverImage, result.CoverImage); + Assert.Equal(library.CoverImage.HasValue ? library.CoverImage.Value : null, result.CoverImage); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); Assert.True(result.CanDownloadMetadataFromWeb); @@ -132,7 +132,7 @@ public class LibraryMappingTests // Assert Assert.NotNull(result); Assert.Equal(library.ContentLocations.Select(l => l.Path), result.ContentLocations.Select(l => l.Path)); - Assert.Equal(library.CoverImage, result.CoverImage); + Assert.Equal(library.CoverImage.HasValue ? library.CoverImage.Value : null, result.CoverImage); } [Fact] 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 new file mode 100644 index 00000000..6c82f2ca --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMappingTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddBookCommandMappingTests +{ + private readonly AddBookCommandFixture _commandBookFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString()); + + // Act + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(libraryId, result.Value.LibraryId.Value); + Assert.Equal(command.Path, result.Value.Path); + Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title); + Assert.Equal(command.Metadata.ReleaseInfo!.OriginalReleaseYear, result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.Equal(command.Metadata.Genres!.Count, result.Value.Metadata.Genres.Count); + Assert.Equal(command.Metadata.Tags!.Count, result.Value.Metadata.Tags.Count); + Assert.Equal(command.ISBNs!.Count, result.Value.ISBNs.Count); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); + Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count); + Assert.True(result.Value.Format.HasValue); + Assert.Equal(command.Format, result.Value.Format.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddBookCommand command = _commandBookFixture.Create( + libraryId: libraryId.ToString(), + 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 + Result result = command.ToDomainEntity(libraryId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(libraryId, result.Value.LibraryId.Value); + Assert.Equal(command.Path, result.Value.Path); + Assert.Empty(result.Value.ISBNs); + Assert.Empty(result.Value.Contributors); + Assert.Empty(result.Value.Ratings); + Assert.False(result.Value.Format.HasValue); + Assert.False(result.Value.Edition.HasValue); + Assert.False(result.Value.VolumeNumber.HasValue); + Assert.False(result.Value.ASIN.HasValue); + Assert.False(result.Value.GoodreadsId.HasValue); + Assert.False(result.Value.LCCN.HasValue); + Assert.False(result.Value.OCLCNumber.HasValue); + Assert.False(result.Value.OpenLibraryId.HasValue); + Assert.False(result.Value.LibraryThingId.HasValue); + Assert.False(result.Value.GoogleBooksId.HasValue); + Assert.False(result.Value.BarnesAndNobleId.HasValue); + Assert.False(result.Value.AppleBooksId.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + AddBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description); + } + + [Fact] + public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError() + { + // Arrange + AddBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + AddBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + + // Act + Result result = command.ToDomainEntity(Guid.NewGuid()); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + } +} 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 d21f7ce5..09d0264e 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; @@ -21,20 +21,22 @@ public class AddBookRequestMappingTests { private readonly AddBookRequestFixture _requestFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); - private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new(); - private readonly MediaContributorRoleDtoFixture _mediaContributorRoleDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); AddBookRequest request = _requestFixture.Create(); // Act - AddBookCommand result = request.ToCommand(); + AddBookCommand result = request.ToCommand(libraryId.ToString()); // Assert Assert.NotNull(result); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(request.Path, result.Path); Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.Format, result.Format); Assert.Equal(request.Edition, result.Edition); @@ -58,15 +60,29 @@ public class AddBookRequestMappingTests public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); AddBookRequest request = _requestFixture.Create( - libraryId: Guid.NewGuid(), path: "/books/test.epub", metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"), - includeOptionalProperties: false + 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 - AddBookCommand result = request.ToCommand(); + AddBookCommand result = request.ToCommand(libraryId.ToString()); // Assert Assert.NotNull(result); @@ -93,24 +109,32 @@ public class AddBookRequestMappingTests public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); AddBookRequest request = _requestFixture.Create( - libraryId: Guid.NewGuid(), path: "/books/test.epub", metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"), isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], contributors: [ - new( - _mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"), - _mediaContributorRoleDtoFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author) - ) + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author) ], ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)], - includeOptionalProperties: false + 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 - AddBookCommand result = request.ToCommand(); + AddBookCommand result = request.ToCommand(libraryId.ToString()); // Assert Assert.NotNull(result); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs index 9847245b..4a75b578 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs @@ -365,73 +365,4 @@ public class BookEntityMappingTests Assert.Equal(paginatedBookEntities.Count, result.Count); Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages); } - - [Fact] - public void ToLiteResponse_WhenMappingBookEntity_ShouldMapIdTitleAndReleaseYear() - { - // Arrange - BookEntity bookEntity = _bookEntityFixture.Create(); - - // Act - BookLiteResponse result = bookEntity.ToLiteResponse(); - - // Assert - Assert.NotNull(result); - Assert.Equal(bookEntity.Id, result.Id); - Assert.Equal(bookEntity.Title, result.Title); - Assert.Equal(bookEntity.ReReleaseYear ?? bookEntity.OriginalReleaseYear, result.ReleaseYear); - Assert.Null(result.CoverPath); - } - - [Fact] - public void ToLiteResponse_WhenBookHasNoReReleaseYear_ShouldFallBackToOriginalReleaseYear() - { - // Arrange - BookEntity bookEntity = _bookEntityFixture.Create(); - bookEntity.ReReleaseYear = null; - - // Act - BookLiteResponse result = bookEntity.ToLiteResponse(); - - // Assert - Assert.Equal(bookEntity.OriginalReleaseYear, result.ReleaseYear); - } - - [Fact] - public void ToLiteResponses_WhenMappingMultipleBookEntities_ShouldMapAllCorrectly() - { - // Arrange - List bookEntities = _bookEntityFixture.CreateMany(2); - - // Act - IReadOnlyList results = bookEntities.ToLiteResponses(); - - // Assert - Assert.NotNull(results); - Assert.Equal(bookEntities.Count, results.Count); - } - - [Fact] - public void ToLiteResponses_WhenMappingPaginatedBookEntities_ShouldMapAllPropertiesCorrectly() - { - // Arrange - List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBookEntities = _paginatedResultDtoFixture.Create( - data: bookEntities, - currentPage: 1, - perPage: 10, - count: 2, - numberOfPages: 1); - - // Act - PaginatedResponse result = paginatedBookEntities.ToLiteResponses(); - - // Assert - Assert.NotNull(result); - Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count); - Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage); - Assert.Equal(paginatedBookEntities.PerPage, result.PerPage); - Assert.Equal(paginatedBookEntities.Count, result.Count); - Assert.Equal(paginatedBookEntities.NumberOfPages, result.NumberOfPages); - } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs new file mode 100644 index 00000000..d061f80f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteRowMappingTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLiteRowMappingTests +{ + private readonly BookLiteRowFixture _bookLiteRowFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingBookLiteRow_ShouldMapAllPropertiesCorrectly() + { + // Arrange + BookLiteRow readModel = _bookLiteRowFixture.Create(); + + // Act + BookLiteResponse result = readModel.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(readModel.Id, result.Id); + Assert.Equal(readModel.Title, result.Title); + Assert.Equal(readModel.ReleaseYear, result.ReleaseYear); + Assert.Equal(readModel.CoverPath, result.CoverPath); + } + + [Fact] + public void ToResponses_WhenMappingMultipleBookLiteRows_ShouldMapAllCorrectly() + { + // Arrange + List readModels = _bookLiteRowFixture.CreateMany(2); + + // Act + IReadOnlyList results = readModels.ToResponses(); + + // Assert + Assert.NotNull(results); + Assert.Equal(readModels.Count, results.Count); + Assert.Equal(readModels.Select(readModel => readModel.Id), results.Select(response => response.Id)); + } + + [Fact] + public void ToResponses_WhenMappingPaginatedBookLiteRows_ShouldMapAllPropertiesCorrectly() + { + // Arrange + List readModels = _bookLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedReadModels = _paginatedResultDtoFixture.Create( + data: readModels, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + + // Act + PaginatedResponse result = paginatedReadModels.ToResponses(); + + // Assert + Assert.NotNull(result); + Assert.Equal(paginatedReadModels.Data.Count, result.Data.Count); + Assert.Equal(paginatedReadModels.CurrentPage, result.CurrentPage); + Assert.Equal(paginatedReadModels.PerPage, result.PerPage); + Assert.Equal(paginatedReadModels.Count, result.Count); + Assert.Equal(paginatedReadModels.NumberOfPages, result.NumberOfPages); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs index 8131f3a8..dae97b83 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs @@ -49,8 +49,9 @@ public class BookMappingTests Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode); Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName); Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName); - Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name)); - Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name)); + // The repository entity stores tags and genres as sets, so duplicate names in the domain collection collapse into a single entry. + Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().Distinct().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name)); + Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().Distinct().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name)); Assert.Equal(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null, result.Publisher); Assert.Equal(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null, result.PageCount); Assert.Equal(book.Format.HasValue ? book.Format.Value : null, result.Format); 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 3c6fd887..40e5383a 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 @@ -24,6 +24,7 @@ public class BookMetadataDtoMappingTests private readonly BookFixture _bookFixture = new(); private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); [Fact] public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItToTheBook() @@ -76,7 +77,7 @@ public class BookMetadataDtoMappingTests { // Arrange Book book = _bookFixture.Create(); - BookMetadataDto metadata = _bookMetadataDtoFixture.Create(title: title, includeOptionalProperties: false); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create(includeTitle: title is not null, title: title, includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false); // Act Result result = book.ApplyMetadata(metadata); @@ -91,7 +92,7 @@ public class BookMetadataDtoMappingTests { // Arrange Book book = _bookFixture.Create(); - BookMetadataDto metadata = _bookMetadataDtoFixture.Create(title: "A valid title", includeOptionalProperties: false); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create(title: "A valid title", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false); // Act Result result = book.ApplyMetadata(metadata); @@ -108,7 +109,7 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "A valid title", - releaseInfo: new ReleaseInfoDto(new DateOnly(2000, 1, 1), 1999, null, null, null, null)); + releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 1999)); // Act Result result = book.ApplyMetadata(metadata); @@ -134,38 +135,6 @@ public class BookMetadataDtoMappingTests Assert.True(result.IsFailure); } - [Fact] - public void ApplyMetadata_WhenLanguageIsInvalid_ShouldReturnError() - { - // Arrange - Book book = _bookFixture.Create(); - BookMetadataDto metadata = _bookMetadataDtoFixture.Create( - title: "A valid title", - language: new LanguageInfoDto("", "English", "English")); - - // Act - Result result = book.ApplyMetadata(metadata); - - // Assert - Assert.True(result.IsFailure); - } - - [Fact] - public void ApplyMetadata_WhenOriginalLanguageIsInvalid_ShouldReturnError() - { - // Arrange - Book book = _bookFixture.Create(); - BookMetadataDto metadata = _bookMetadataDtoFixture.Create( - title: "A valid title", - originalLanguage: new LanguageInfoDto("", "English", "English")); - - // Act - Result result = book.ApplyMetadata(metadata); - - // Assert - Assert.True(result.IsFailure); - } - [Fact] public void ApplyMetadata_WhenIsbnIsInvalid_ShouldReturnError() { @@ -205,8 +174,12 @@ public class BookMetadataDtoMappingTests Book book = _bookFixture.Create(); BookMetadataDto metadata = _bookMetadataDtoFixture.Create( title: "A valid title", - releaseInfo: new ReleaseInfoDto(new DateOnly(2000, 1, 1), 2000, null, null, null, null), - includeOptionalProperties: false); + releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2000, 1, 1), originalReleaseYear: 2000), + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false); // Act Result result = book.ApplyMetadata(metadata); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMappingTests.cs deleted file mode 100644 index 4c3dbcab..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestMappingTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetBookRequestMappingTests -{ - private readonly GetBookRequestFixture _requestFixture = new(); - - [Fact] - public void ToQuery_WhenMappingRequestWithValidId_ShouldMapIdCorrectly() - { - // Arrange - Guid bookId = Guid.NewGuid(); - GetBookRequest request = _requestFixture.Create(id: bookId.ToString()); - - // Act - GetBookQuery result = request.ToQuery(); - - // Assert - Assert.Equal(bookId, result.Id); - } - - [Fact] - public void ToQuery_WhenMappingRequestWithInvalidId_ShouldMapEmptyGuid() - { - // Arrange - GetBookRequest request = _requestFixture.Create(id: "not-a-guid"); - - // Act - GetBookQuery result = request.ToQuery(); - - // Assert - Assert.Equal(Guid.Empty, result.Id); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs index 9a603ef4..0f1f5b1e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,14 +22,17 @@ public class GetBooksLiteRequestMappingTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); - Assert.Equal(request.SearchTerm, result.Filter.SearchTerm); + Assert.Equal(libraryId, result.LibraryId); + Assert.Equal(request.SearchTerm, result.SearchTerm); + Assert.Equal(request.FilterAlphaKey, result.FilterAlphaKey); + Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(request.SortBy, result.SortBy); Assert.Equal(request.SortOrder, result.SortOrder); Assert.NotNull(result.PaginationData); @@ -36,19 +40,49 @@ public class GetBooksLiteRequestMappingTests Assert.Equal(request.PerPage, result.PaginationData.PerPage); } + [Fact] + public void ToQuery_WhenLibraryIdIsNotParseable_ShouldMapItAsIs() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + string libraryId = "not-a-library-guid"; + + // Act + GetBooksLiteQuery result = request.ToQuery(libraryId); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId, result.LibraryId); + } + + [Fact] + public void ToQuery_WhenLibraryIdIsNull_ShouldMapNullLibraryId() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + + // Act + GetBooksLiteQuery result = request.ToQuery(null); + + // Assert + Assert.NotNull(result); + Assert.Null(result.LibraryId); + } + [Fact] public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); Assert.Null(result.PaginationData); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); + Assert.Equal(libraryId, result.LibraryId); } [Fact] @@ -56,9 +90,10 @@ public class GetBooksLiteRequestMappingTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(perPage: 25, includeCurrentPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); @@ -71,9 +106,10 @@ public class GetBooksLiteRequestMappingTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(currentPage: 3, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksLiteQuery result = request.ToQuery(); + GetBooksLiteQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs index fffc881b..01134ff2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestMappingTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,14 +22,15 @@ public class GetBooksRequestMappingTests { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); - Assert.Equal(request.SearchTerm, result.Filter.SearchTerm); + Assert.Equal(libraryId, result.LibraryId); + Assert.Equal(request.SearchTerm, result.SearchTerm); Assert.Equal(request.SortBy, result.SortBy); Assert.Equal(request.SortOrder, result.SortOrder); Assert.NotNull(result.PaginationData); @@ -36,19 +38,49 @@ public class GetBooksRequestMappingTests Assert.Equal(request.PerPage, result.PaginationData.PerPage); } + [Fact] + public void ToQuery_WhenLibraryIdIsNotParseable_ShouldMapItAsIs() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + string libraryId = "not-a-library-guid"; + + // Act + GetBooksQuery result = request.ToQuery(libraryId); + + // Assert + Assert.NotNull(result); + Assert.Equal(libraryId, result.LibraryId); + } + + [Fact] + public void ToQuery_WhenLibraryIdIsNull_ShouldMapNullLibraryId() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + + // Act + GetBooksQuery result = request.ToQuery(null); + + // Assert + Assert.NotNull(result); + Assert.Null(result.LibraryId); + } + [Fact] public void ToQuery_WhenNoPaginationProvided_ShouldNotBuildPaginationData() { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result); Assert.Null(result.PaginationData); - Assert.Equal(request.LibraryId, result.Filter.LibraryId); + Assert.Equal(libraryId, result.LibraryId); } [Fact] @@ -56,9 +88,10 @@ public class GetBooksRequestMappingTests { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(perPage: 25, includeCurrentPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); @@ -71,9 +104,10 @@ public class GetBooksRequestMappingTests { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(currentPage: 3, includePerPage: false); + string libraryId = Guid.NewGuid().ToString(); // Act - GetBooksQuery result = request.ToQuery(); + GetBooksQuery result = request.ToQuery(libraryId); // Assert Assert.NotNull(result.PaginationData); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs deleted file mode 100644 index 697d16a1..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetReadingAvailabilityRequestMappingTests -{ - private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new(); - - [Fact] - public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); - - // Act - GetReadingAvailabilityQuery result = request.ToQuery(); - - // Assert - Assert.Equal(request.BookId, result.BookId); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMappingTests.cs deleted file mode 100644 index 373fdabb..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMappingTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetReadingManifestRequestMappingTests -{ - private readonly GetReadingManifestRequestFixture _requestFixture = new(); - - [Fact] - public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - GetReadingManifestRequest request = _requestFixture.Create(); - - // Act - GetReadingManifestQuery result = request.ToQuery(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.BookId, result.BookId); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMappingTests.cs deleted file mode 100644 index ca42e096..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMappingTests.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetReadingResourceRequestMappingTests -{ - private readonly GetReadingResourceRequestFixture _requestFixture = new(); - - [Fact] - public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - GetReadingResourceRequest request = _requestFixture.Create(); - - // Act - GetReadingResourceQuery result = request.ToQuery(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.BookId, result.BookId); - Assert.Equal(request.ResourceKey, result.ResourceKey); - } -} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMappingTests.cs deleted file mode 100644 index 088beb6d..00000000 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMappingTests.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class GetReadingSectionRequestMappingTests -{ - private readonly GetReadingSectionRequestFixture _requestFixture = new(); - - [Fact] - public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() - { - // Arrange - GetReadingSectionRequest request = _requestFixture.Create(); - - // Act - GetReadingSectionQuery result = request.ToQuery(); - - // Assert - Assert.NotNull(result); - Assert.Equal(request.BookId, result.BookId); - Assert.Equal(request.LocationRef, result.LocationRef); - } -} 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 f913bdd4..c89839e2 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 @@ -1,8 +1,17 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -14,45 +23,136 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookCommandMappingTests { - private readonly UpdateBookCommandFixture _commandFixture = new(); + private readonly UpdateBookCommandFixture _commandBookFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); [Fact] - public void ToBookMetadataDto_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() + public void ToDomainEntity_WhenMappingCompleteCommand_ShouldMapAllPropertiesCorrectly() { // Arrange - UpdateBookCommand command = _commandFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + UpdateBookCommand command = _commandBookFixture.Create(libraryId: libraryId.ToString(), bookId: bookId.ToString()); + BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub"); + DateTime createdOnUtc = existingBook.CreatedOnUtc; // Act - BookMetadataDto result = command.ToBookMetadataDto(); + Result result = command.ToDomainEntity(existingBook); // Assert - Assert.NotNull(result); - Assert.Equal(command.Metadata!.Title, result.Title); - Assert.Equal(command.Metadata.OriginalTitle, result.OriginalTitle); - Assert.Equal(command.Metadata.Description, result.Description); - Assert.Equal(command.Metadata.ReleaseInfo, result.ReleaseInfo); - Assert.Equal(command.Metadata.Genres, result.Genres); - Assert.Equal(command.Metadata.Tags, result.Tags); - Assert.Equal(command.Metadata.Language, result.Language); - Assert.Equal(command.Metadata.OriginalLanguage, result.OriginalLanguage); - Assert.Equal(command.Metadata.Publisher, result.Publisher); - Assert.Equal(command.Metadata.PageCount, result.PageCount); - Assert.Equal(command.Format, result.Format); - Assert.Equal(command.Edition, result.Edition); - Assert.Equal(command.VolumeNumber, result.VolumeNumber); - Assert.Equal(command.Series, result.Series); - Assert.Equal(command.ASIN, result.ASIN); - Assert.Equal(command.GoodreadsId, result.GoodreadsId); - Assert.Equal(command.LCCN, result.LCCN); - Assert.Equal(command.OCLCNumber, result.OCLCNumber); - Assert.Equal(command.OpenLibraryId, result.OpenLibraryId); - Assert.Equal(command.LibraryThingId, result.LibraryThingId); - Assert.Equal(command.GoogleBooksId, result.GoogleBooksId); - Assert.Equal(command.BarnesAndNobleId, result.BarnesAndNobleId); - Assert.Equal(command.AppleBooksId, result.AppleBooksId); - Assert.Equal(command.ISBNs, result.Isbns); - Assert.Equal(command.Contributors, result.Contributors); - Assert.Equal(command.Ratings, result.Ratings); - Assert.Null(result.CoverImagePath); + Assert.False(result.IsFailure); + Assert.Equal(bookId, result.Value.Id.Value); + Assert.Equal(libraryId, result.Value.LibraryId.Value); + Assert.Equal(existingBook.Path, result.Value.Path); + Assert.Equal(createdOnUtc, result.Value.CreatedOnUtc); + Assert.Equal(command.Metadata!.Title, result.Value.Metadata.Title); + Assert.Equal(command.Metadata.ReleaseInfo!.OriginalReleaseYear, result.Value.Metadata.ReleaseInfo.OriginalReleaseYear.Value); + Assert.Equal(command.Metadata.Genres!.Count, result.Value.Metadata.Genres.Count); + Assert.Equal(command.Metadata.Tags!.Count, result.Value.Metadata.Tags.Count); + Assert.Equal(command.ISBNs!.Count, result.Value.ISBNs.Count); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors.Count); + Assert.Equal(command.Ratings!.Count, result.Value.Ratings.Count); + Assert.True(result.Value.Format.HasValue); + Assert.Equal(command.Format, result.Value.Format.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalPropertiesAreMissing_ShouldMapRequiredPropertiesCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + UpdateBookCommand command = _commandBookFixture.Create( + libraryId: libraryId.ToString(), + bookId: bookId.ToString(), + 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); + BookEntity existingBook = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: "/books/the-book.epub"); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(bookId, result.Value.Id.Value); + Assert.Equal(libraryId, result.Value.LibraryId.Value); + Assert.Equal(existingBook.Path, result.Value.Path); + Assert.Empty(result.Value.ISBNs); + Assert.Empty(result.Value.Contributors); + Assert.Empty(result.Value.Ratings); + Assert.False(result.Value.Format.HasValue); + Assert.False(result.Value.Edition.HasValue); + Assert.False(result.Value.VolumeNumber.HasValue); + Assert.False(result.Value.ASIN.HasValue); + Assert.False(result.Value.GoodreadsId.HasValue); + Assert.False(result.Value.LCCN.HasValue); + Assert.False(result.Value.OCLCNumber.HasValue); + Assert.False(result.Value.OpenLibraryId.HasValue); + Assert.False(result.Value.LibraryThingId.HasValue); + Assert.False(result.Value.GoogleBooksId.HasValue); + Assert.False(result.Value.BarnesAndNobleId.HasValue); + Assert.False(result.Value.AppleBooksId.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenRatingCreationFails_ShouldReturnError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); + BookEntity existingBook = _bookEntityFixture.Create(); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description); + } + + [Fact] + public void ToDomainEntity_WhenIsbnCreationFails_ShouldReturnError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + BookEntity existingBook = _bookEntityFixture.Create(); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); + } + + [Fact] + public void ToDomainEntity_WhenMetadataCreationFails_ShouldReturnError() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")])); + BookEntity existingBook = _bookEntityFixture.Create(); + + // Act + Result result = command.ToDomainEntity(existingBook); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); } } 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 new file mode 100644 index 00000000..9d47b1c4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMappingTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateBookCoverCommandMappingTests +{ + private readonly UpdateBookCoverCommandFixture _commandFixture = new(); + private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenBookHasNoCover_ShouldReturnANewEnrichedCoverArtwork() + { + // Arrange + Guid userId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + UpdateBookCoverCommand command = _commandFixture.Create(bookId: bookId.ToString()); + string storedCoverPath = "/media/books/cover.jpg"; + + // Act + BookArtworkEntity cover = command.ToRepositoryEntity(null, bookId, storedCoverPath, userId); + + // Assert + Assert.Equal(bookId, cover.BookId); + Assert.Equal(ArtworkType.Cover, cover.ArtworkType); + Assert.Equal(0, cover.Ordinal); + Assert.Equal(storedCoverPath, cover.FileName); + Assert.Equal(ArtworkStatus.Enriched, cover.Status); + Assert.Equal(userId, cover.CreatedBy); + Assert.NotEqual(default, cover.CreatedOnUtc); + Assert.Null(cover.UpdatedBy); + } + + [Fact] + public void ToRepositoryEntity_WhenBookHasAnExistingCover_ShouldReplaceAndReturnTheStoredCover() + { + // Arrange + Guid userId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + UpdateBookCoverCommand command = _commandFixture.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"; + + // Act + BookArtworkEntity cover = command.ToRepositoryEntity(existingCover, bookId, storedCoverPath, userId); + + // Assert + Assert.Same(existingCover, cover); + Assert.Equal(storedCoverPath, cover.FileName); + Assert.Equal(ArtworkStatus.Enriched, cover.Status); + Assert.Equal(userId, cover.UpdatedBy); + Assert.NotNull(cover.UpdatedOnUtc); + Assert.NotNull(cover.LastUpdateUtc); + } +} 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 20937a11..0b3a9bf8 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,6 +1,7 @@ -#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; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -18,20 +19,23 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten public class UpdateBookRequestMappingTests { private readonly UpdateBookRequestFixture _requestFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create(id: bookId); + UpdateBookRequest request = _requestFixture.Create(); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); // Assert Assert.NotNull(result); - Assert.Equal(bookId, result.Id); + Assert.Equal(libraryId.ToString(), result.LibraryId); + Assert.Equal(bookId.ToString(), result.BookId); Assert.Equal(request.Metadata, result.Metadata); Assert.Equal(request.Format, result.Format); Assert.Equal(request.Edition, result.Edition); @@ -55,15 +59,16 @@ public class UpdateBookRequestMappingTests public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - UpdateBookRequest request = _requestFixture.Create(id: bookId, includeOptionalProperties: false); + 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); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); // Assert Assert.NotNull(result); - Assert.Equal(bookId, result.Id); + Assert.Equal(bookId.ToString(), result.BookId); Assert.NotNull(result.Metadata); Assert.Equal(request.Metadata, result.Metadata); Assert.Null(result.Format); @@ -88,21 +93,31 @@ public class UpdateBookRequestMappingTests public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() { // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); UpdateBookRequest request = _requestFixture.Create( isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], contributors: [ - new( - new("John Doe", "John Smith Doe"), - new("Author", MediaContributorRoleCategory.Author) - ) + _mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author) ], ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)], - includeOptionalProperties: false + 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 - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand(libraryId.ToString(), bookId.ToString()); // Assert Assert.NotNull(result); @@ -112,41 +127,16 @@ public class UpdateBookRequestMappingTests } [Fact] - public void ToCommand_WhenMappingRequestWithNullId_ShouldMapEmptyGuid() + public void ToCommand_WhenRouteValuesAreNotParseable_ShouldMapThemAsIs() { // Arrange - UpdateBookRequest request = _requestFixture.Create(includeId: false); + 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); // Act - UpdateBookCommand result = request.ToCommand(); + UpdateBookCommand result = request.ToCommand("not-a-library-guid", "not-a-guid"); // Assert - Assert.Equal(Guid.Empty, result.Id); - } - - [Fact] - public void ToCommand_WhenMappingRequestWithEmptyId_ShouldMapEmptyGuid() - { - // Arrange - UpdateBookRequest request = _requestFixture.Create(rawId: string.Empty); - - // Act - UpdateBookCommand result = request.ToCommand(); - - // Assert - Assert.Equal(Guid.Empty, result.Id); - } - - [Fact] - public void ToCommand_WhenMappingRequestWithUnparseableId_ShouldMapEmptyGuid() - { - // Arrange - UpdateBookRequest request = _requestFixture.Create(rawId: "not-a-guid"); - - // Act - UpdateBookCommand result = request.ToCommand(); - - // Assert - Assert.Equal(Guid.Empty, result.Id); + Assert.Equal("not-a-library-guid", result.LibraryId); + Assert.Equal("not-a-guid", result.BookId); } } 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 fe558119..d859ed13 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 @@ -56,7 +56,7 @@ public class BookRatingDtoMappingTests public void ToDomainEntity_WhenMappingMinimalBookRatingDto_ShouldMapRequiredPropertiesCorrectly() { // Arrange - BookRatingDto dto = _bookRatingDtoFixture.Create(includeOptionalProperties: false); + BookRatingDto dto = _bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false); // Act Result result = dto.ToDomainEntity(); @@ -90,7 +90,7 @@ public class BookRatingDtoMappingTests List dtos = [ _bookRatingDtoFixture.Create(), - _bookRatingDtoFixture.Create(includeOptionalProperties: false) + _bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false) ]; // Act @@ -125,7 +125,7 @@ public class BookRatingDtoMappingTests [ _bookRatingDtoFixture.Create(), _bookRatingDtoFixture.Create(value: 10, maxValue: 5), - _bookRatingDtoFixture.Create(includeOptionalProperties: false) + _bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false) ]; // Act 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 new file mode 100644 index 00000000..10def379 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMappingTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataDtoMappingTests +{ + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingCompleteWrittenContentMetadataDto_ShouldMapAllPropertiesCorrectly() + { + // Arrange + WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(dto.Title, result.Value.Title); + Assert.True(result.Value.OriginalTitle.HasValue); + Assert.Equal(dto.OriginalTitle, result.Value.OriginalTitle.Value); + Assert.True(result.Value.Description.HasValue); + Assert.Equal(dto.Description, result.Value.Description.Value); + Assert.Equal(dto.Genres!.Count, result.Value.Genres.Count); + Assert.Equal(dto.Tags!.Count, result.Value.Tags.Count); + Assert.True(result.Value.Language.HasValue); + Assert.Equal(dto.Language!.LanguageCode!.ToLowerInvariant(), result.Value.Language.Value.LanguageCode); + Assert.True(result.Value.OriginalLanguage.HasValue); + Assert.Equal(dto.OriginalLanguage!.LanguageCode!.ToLowerInvariant(), result.Value.OriginalLanguage.Value.LanguageCode); + Assert.True(result.Value.Publisher.HasValue); + Assert.Equal(dto.Publisher, result.Value.Publisher.Value); + Assert.True(result.Value.PageCount.HasValue); + Assert.Equal(dto.PageCount!.Value, result.Value.PageCount.Value); + } + + [Fact] + public void ToDomainEntity_WhenOptionalValuesAreMissing_ShouldMapWithoutOptionalValues() + { + // Arrange + WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create( + includeOriginalTitle: false, + includeDescription: false, + includeLanguage: false, + includeOriginalLanguage: false, + includePublisher: false, + includePageCount: false); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.OriginalTitle.HasValue); + Assert.False(result.Value.Description.HasValue); + Assert.False(result.Value.Language.HasValue); + Assert.False(result.Value.OriginalLanguage.HasValue); + Assert.False(result.Value.Publisher.HasValue); + Assert.False(result.Value.PageCount.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenReleaseInfoCreationFails_ShouldReturnError() + { + // Arrange + WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create( + releaseInfo: _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2025, 1, 1), + originalReleaseYear: 2024)); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ToDomainEntity_WhenGenreCreationFails_ShouldReturnError() + { + // Arrange + WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: "")]); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public void ToDomainEntity_WhenTagCreationFails_ShouldReturnError() + { + // Arrange + WrittenContentMetadataDto dto = _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: "")]); + + // Act + Result result = dto.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + } +} 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 f43abf85..fbaa8787 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -46,6 +48,7 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService = Substitute.For(); _mockPermissionRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _userId = Guid.NewGuid(); _mockCurrentUserService.UserId.Returns(_userId); @@ -62,7 +65,7 @@ public class GetPermissionsQueryHandlerTests { // Arrange GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); - IEnumerable permissions = + List permissions = [ _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers), _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers) @@ -70,8 +73,8 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockPermissionRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(permissions)); + _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = permissions, CurrentPage = 1, PerPage = permissions.Count, Count = permissions.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -80,7 +83,7 @@ public class GetPermissionsQueryHandlerTests Assert.False(result.IsFailure); Assert.Equal(2, result.Value.Count()); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockPermissionRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -99,7 +102,7 @@ public class GetPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPermissionRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -116,7 +119,7 @@ public class GetPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPermissionRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -128,7 +131,7 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockPermissionRepository.GetAllAsync(Arg.Any()) + _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -138,7 +141,7 @@ public class GetPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockPermissionRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -146,7 +149,7 @@ public class GetPermissionsQueryHandlerTests { // Arrange GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); - IEnumerable permissions = + List permissions = [ _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers) ]; @@ -154,8 +157,8 @@ public class GetPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockPermissionRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(permissions)); + _mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = permissions, CurrentPage = 1, PerPage = permissions.Count, Count = permissions.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, cancellationToken); @@ -164,6 +167,6 @@ public class GetPermissionsQueryHandlerTests Assert.False(result.IsFailure); Assert.Single(result.Value); await _mockAuthorizationService.Received(1).IsInRoleAsync(_userId, "Admin", Arg.Any()); - await _mockPermissionRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockPermissionRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index aadc14c4..b892e1c4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class AddRoleCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index 5976f727..4e51668b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -43,6 +43,7 @@ public class DeleteRoleCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -89,7 +90,7 @@ public class DeleteRoleCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -100,7 +101,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -121,7 +122,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(adminRole); // Act @@ -142,7 +143,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -164,7 +165,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(role); _mockRoleRepository.DeleteByIdAsync(command.RoleId, Arg.Any()) .Returns(error); @@ -187,7 +188,7 @@ public class DeleteRoleCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(role); _mockRoleRepository.DeleteByIdAsync(command.RoleId, Arg.Any()) .Returns(Result.Deleted); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index 25e4bc67..4bfdef9a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class UpdateRoleCommandHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -130,7 +131,7 @@ public class UpdateRoleCommandHandlerTests .Returns(true); _mockRoleRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -151,7 +152,7 @@ public class UpdateRoleCommandHandlerTests .Returns(true); _mockRoleRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -178,7 +179,7 @@ public class UpdateRoleCommandHandlerTests .Returns(true); _mockRoleRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); - _mockRoleRepository.GetByIdAsync(command.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId, cancellationToken: Arg.Any()) .Returns(role); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index 2692d0bc..773b3828 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -47,6 +47,7 @@ public class GetRolePermissionsQueryHandlerTests mockValidator.Validate(Arg.Any()) .Returns([]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -76,7 +77,7 @@ public class GetRolePermissionsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -93,7 +94,7 @@ public class GetRolePermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -105,7 +106,7 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(query.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(query.RoleId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -124,7 +125,7 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(query.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(query.RoleId, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -153,7 +154,7 @@ public class GetRolePermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetByIdAsync(query.RoleId, Arg.Any()) + _mockRoleRepository.GetByIdAsync(query.RoleId, cancellationToken: Arg.Any()) .Returns(role); // Act 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 ddec5b2f..7569ad9f 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -41,6 +43,7 @@ public class GetRolesQueryHandlerTests public GetRolesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockRoleRepository = Substitute.For(); @@ -69,7 +72,7 @@ public class GetRolesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -86,7 +89,7 @@ public class GetRolesQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -98,7 +101,7 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetAllAsync(Arg.Any()) + _mockRoleRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -114,7 +117,7 @@ public class GetRolesQueryHandlerTests { // Arrange GetRolesQuery query = _getRolesQueryFixture.Create(); - IEnumerable roles = + List roles = [ _roleEntityFixture.Create(roleName: "Admin"), _roleEntityFixture.Create(roleName: "User") @@ -122,8 +125,8 @@ public class GetRolesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockRoleRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(roles)); + _mockRoleRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { 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/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs index 0efb2263..1ce93265 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandlerTests.cs @@ -49,11 +49,11 @@ public class GetDirectoriesQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQueryWithoutFilesIncluded_ShouldReturnSuccessResult() { // Arrange - GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: false); + GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(shouldIncludeHiddenElements: false); IEnumerable directories = _directoryFixture.CreateMany(); - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.ShouldIncludeHiddenElements) .Returns(Result.From(directories)); // Act @@ -76,18 +76,18 @@ public class GetDirectoriesQueryHandlerTests Assert.Empty(resultList[i].Items); // since files are not included } - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.ShouldIncludeHiddenElements); } [Fact] public async Task HandleAsync_WhenCalledWithValidQueryWithFilesIncluded_ShouldReturnSuccessResult() { // Arrange - GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(includeHiddenElements: true); + GetDirectoriesQuery getDirectoriesQuery = _getDirectoriesQueryFixture.Create(shouldIncludeHiddenElements: true); IEnumerable directories = _directoryFixture.CreateMany(); - _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.ShouldIncludeHiddenElements) .Returns(Result.From(directories)); // Act @@ -110,7 +110,7 @@ public class GetDirectoriesQueryHandlerTests Assert.Equal(directoriesList[i].Items.Count, resultList[i].Items.Count); } - _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.IncludeHiddenElements); + _mockDirectoryService.Received(1).GetSubdirectories(getDirectoriesQuery.Path!, getDirectoriesQuery.ShouldIncludeHiddenElements); } [Fact] @@ -119,7 +119,7 @@ public class GetDirectoriesQueryHandlerTests // Arrange GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); Error error = Error.Failure("DirectoryService.Error", "An error occurred"); - _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(query.Path!, query.ShouldIncludeHiddenElements) .Returns(error); // Act @@ -128,7 +128,7 @@ public class GetDirectoriesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.ShouldIncludeHiddenElements); } [Fact] @@ -137,7 +137,7 @@ public class GetDirectoriesQueryHandlerTests // Arrange GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); - _mockDirectoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements) + _mockDirectoryService.GetSubdirectories(query.Path!, query.ShouldIncludeHiddenElements) .Returns(emptyList); // Act @@ -146,6 +146,6 @@ public class GetDirectoriesQueryHandlerTests // Assert Assert.False(result.IsFailure); Assert.Empty(result.Value); - _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.IncludeHiddenElements); + _mockDirectoryService.Received(1).GetSubdirectories(query.Path!, query.ShouldIncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs index 055c3ef5..85b458e6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidatorTests.cs @@ -76,11 +76,11 @@ public class GetDirectoriesQueryValidatorTests } [Fact] - public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + public void Validate_WhenShouldIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() { // Arrange GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); - query = query with { IncludeHiddenElements = true }; + query = query with { ShouldIncludeHiddenElements = true }; // Act List result = _validator.TestValidate(query); @@ -90,11 +90,11 @@ public class GetDirectoriesQueryValidatorTests } [Fact] - public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + public void Validate_WhenShouldIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() { // Arrange GetDirectoriesQuery query = _getDirectoriesQueryFixture.Create(); - query = query with { IncludeHiddenElements = false }; + query = query with { ShouldIncludeHiddenElements = false }; // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs index 0ffcb560..019d00b5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryHandlerTests.cs @@ -49,11 +49,11 @@ public class GetFilesQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: false); + GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(shouldIncludeHiddenElements: false); IEnumerable files = _fileFixture.CreateMany(); - _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements) .Returns(Result.From(files)); // Act @@ -76,18 +76,18 @@ public class GetFilesQueryHandlerTests Assert.Equal(filesList[i].Size, resultList[i].Size); } - _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements); } [Fact] public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(includeHiddenElements: true); + GetFilesQuery getFilesQuery = _getFilesQueryFixture.Create(shouldIncludeHiddenElements: true); IEnumerable files = _fileFixture.CreateMany(); - _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements) .Returns(Result.From(files)); // Act @@ -110,7 +110,7 @@ public class GetFilesQueryHandlerTests Assert.Equal(filesList[i].Size, resultList[i].Size); } - _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements); } [Fact] @@ -119,7 +119,7 @@ public class GetFilesQueryHandlerTests // Arrange GetFilesQuery query = _getFilesQueryFixture.Create(); Error error = Error.Failure("FileService.Error", "An error occurred"); - _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.ShouldIncludeHiddenElements) .Returns(error); // Act @@ -128,7 +128,7 @@ public class GetFilesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(query.Path!, query.ShouldIncludeHiddenElements); } [Fact] @@ -137,7 +137,7 @@ public class GetFilesQueryHandlerTests // Arrange GetFilesQuery query = _getFilesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); - _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.ShouldIncludeHiddenElements) .Returns(emptyList); // Act @@ -146,6 +146,6 @@ public class GetFilesQueryHandlerTests // Assert Assert.False(result.IsFailure); Assert.Empty(result.Value); - _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(query.Path!, query.ShouldIncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs index 4cd5eeb6..7383e3ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetFiles/GetFilesQueryValidatorTests.cs @@ -76,11 +76,11 @@ public class GetFilesQueryValidatorTests } [Fact] - public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + public void Validate_WhenShouldIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() { // Arrange GetFilesQuery query = _getFilesQueryFixture.Create(); - query = query with { IncludeHiddenElements = true }; + query = query with { ShouldIncludeHiddenElements = true }; // Act List result = _validator.TestValidate(query); @@ -90,11 +90,11 @@ public class GetFilesQueryValidatorTests } [Fact] - public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + public void Validate_WhenShouldIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() { // Arrange GetFilesQuery query = _getFilesQueryFixture.Create(); - query = query with { IncludeHiddenElements = false }; + query = query with { ShouldIncludeHiddenElements = false }; // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs index 8d0809db..b237d0ee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryHandlerTests.cs @@ -49,11 +49,11 @@ public class GetTreeFilesQueryHandlerTests public async Task HandleAsync_WhenCalledWithValidQueryWithoutHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: false); + GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(shouldIncludeHiddenElements: false); IEnumerable files = _fileFixture.CreateMany(); - _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements) .Returns(Result.From(files)); // Act @@ -77,18 +77,18 @@ public class GetTreeFilesQueryHandlerTests Assert.Empty(resultList[i].Children); } - _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements); } [Fact] public async Task HandleAsync_WhenCalledWithValidQueryWithHiddenFiles_ShouldReturnSuccessResult() { // Arrange - GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(includeHiddenElements: true); + GetTreeFilesQuery getFilesQuery = _getTreeFilesQueryFixture.Create(shouldIncludeHiddenElements: true); IEnumerable files = _fileFixture.CreateMany(); - _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements) + _mockFileService.GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements) .Returns(Result.From(files)); // Act @@ -112,7 +112,7 @@ public class GetTreeFilesQueryHandlerTests Assert.Empty(resultList[i].Children); } - _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(getFilesQuery.Path!, getFilesQuery.ShouldIncludeHiddenElements); } [Fact] @@ -121,7 +121,7 @@ public class GetTreeFilesQueryHandlerTests // Arrange GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); Error error = Error.Failure("FileService.Error", "An error occurred"); - _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.ShouldIncludeHiddenElements) .Returns(error); // Act @@ -130,7 +130,7 @@ public class GetTreeFilesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(query.Path!, query.ShouldIncludeHiddenElements); } [Fact] @@ -139,7 +139,7 @@ public class GetTreeFilesQueryHandlerTests // Arrange GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); Result> emptyList = Result.From(Enumerable.Empty()); - _mockFileService.GetFiles(query.Path!, query.IncludeHiddenElements) + _mockFileService.GetFiles(query.Path!, query.ShouldIncludeHiddenElements) .Returns(emptyList); // Act @@ -148,6 +148,6 @@ public class GetTreeFilesQueryHandlerTests // Assert Assert.False(result.IsFailure); Assert.Empty(result.Value); - _mockFileService.Received(1).GetFiles(query.Path!, query.IncludeHiddenElements); + _mockFileService.Received(1).GetFiles(query.Path!, query.ShouldIncludeHiddenElements); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs index af7e9e65..40d47395 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Files/Queries/GetTreeFiles/GetTreeFilesQueryValidatorTests.cs @@ -76,11 +76,11 @@ public class GetTreeFilesQueryValidatorTests } [Fact] - public void Validate_WhenIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() + public void Validate_WhenShouldIncludeHiddenElementsIsTrue_ShouldNotHaveValidationError() { // Arrange GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); - query = query with { IncludeHiddenElements = true }; + query = query with { ShouldIncludeHiddenElements = true }; // Act List result = _validator.TestValidate(query); @@ -90,11 +90,11 @@ public class GetTreeFilesQueryValidatorTests } [Fact] - public void Validate_WhenIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() + public void Validate_WhenShouldIncludeHiddenElementsIsFalse_ShouldNotHaveValidationError() { // Arrange GetTreeFilesQuery query = _getTreeFilesQueryFixture.Create(); - query = query with { IncludeHiddenElements = false }; + query = query with { ShouldIncludeHiddenElements = false }; // Act List result = _validator.TestValidate(query); 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 5c46c28a..45bd4ffc 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 @@ -52,10 +52,10 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse() + public async Task HandleAsync_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrueResponse() { // Arrange - CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: true); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(shouldIncludeHiddenElements: true); _mockPathService.Exists(query.Path!).Returns(true); // Act @@ -68,10 +68,10 @@ public class CheckPathExistsQueryHandlerTests } [Fact] - public async Task HandleAsync_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse() + public async Task HandleAsync_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalseResponse() { // Arrange - CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(includeHiddenElements: false); + CheckPathExistsQuery query = _checkPathExistsQueryFixture.Create(shouldIncludeHiddenElements: false); _mockPathService.Exists(query.Path!, false).Returns(false); // Act 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 685422b6..7e22e841 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 @@ -5,6 +5,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; @@ -22,7 +24,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Scheduling; using NSubstitute; using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -57,6 +58,7 @@ public class SetupApplicationCommandHandlerTests public SetupApplicationCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); @@ -75,8 +77,8 @@ public class SetupApplicationCommandHandlerTests _mockDateTimeProvider.UtcNow.Returns(DateTime.UtcNow); _mockDataSeedService.SetDefaultScheduledJobsAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new SetupApplicationCommandHandler( _mockUnitOfWork, @@ -97,8 +99,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create() with { Use2fa = false }; string hashedPassword = Uri.EscapeDataString("hashedPassword"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) @@ -121,7 +123,7 @@ public class SetupApplicationCommandHandlerTests Assert.Equal(command.Username, result.Value.Username); Assert.Null(result.Value.TotpSecret); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -136,8 +138,8 @@ public class SetupApplicationCommandHandlerTests string qrCodeUri = "data:image/png;base64,test"; string encryptedSecret = "encryptedSecret"; - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockHashService.HashString(command.Password!) .Returns(hashedPassword); _mockTotpTokenGenerator.GenerateSecret() @@ -166,7 +168,7 @@ public class SetupApplicationCommandHandlerTests Assert.Equal(command.Username, result.Value.Username); Assert.Equal(qrCodeUri, result.Value.TotpSecret); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -178,8 +180,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); UserEntity existingUser = _userEntityFixture.Create(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(new[] { existingUser }); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [existingUser], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -188,7 +190,7 @@ public class SetupApplicationCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.AdminAccountAlreadyCreated, result.FirstError); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -200,7 +202,7 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to retrieve users"); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -210,7 +212,7 @@ public class SetupApplicationCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -222,8 +224,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to insert user"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(error); @@ -234,7 +236,7 @@ public class SetupApplicationCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -246,8 +248,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set default permissions"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -271,8 +273,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set default roles"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -299,8 +301,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set admin role permissions"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -330,8 +332,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to set admin role to administrator account"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -364,8 +366,8 @@ public class SetupApplicationCommandHandlerTests SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to seed default scheduled jobs"); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -396,8 +398,8 @@ public class SetupApplicationCommandHandlerTests // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -433,8 +435,8 @@ public class SetupApplicationCommandHandlerTests ScheduledJobEntity activeScheduledJob2 = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active); ScheduledJobEntity addedScheduledJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); _mockDataSeedService.SetDefaultAuthorizationPermissionsAsync(Arg.Any(), Arg.Any()) @@ -445,8 +447,15 @@ public class SetupApplicationCommandHandlerTests .Returns(Result.Created); _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) .Returns(Result.Created); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(new[] { activeScheduledJob1, activeScheduledJob2, addedScheduledJob }); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto + { + Data = [activeScheduledJob1, activeScheduledJob2, addedScheduledJob], + CurrentPage = 1, + PerPage = 3, + Count = 3, + NumberOfPages = 1 + })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -472,7 +481,7 @@ public class SetupApplicationCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(validationError, result.FirstError); - await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); await _mockUserRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); } @@ -481,8 +490,8 @@ public class SetupApplicationCommandHandlerTests { // Arrange SetupApplicationCommand command = _setupApplicationCommandFixture.Create(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockHashService.HashString(command.Password!) .Returns("hashedPassword"); _mockUserRepository.InsertAsync(Arg.Any(), Arg.Any()) @@ -496,7 +505,7 @@ public class SetupApplicationCommandHandlerTests _mockDataSeedService.SetAdminRoleToAdministratorAccount(Arg.Any(), Arg.Any()) .Returns(Result.Created); Error expectedError = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(expectedError); // 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 7771223e..c53ae29f 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +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.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; @@ -10,7 +12,6 @@ using Lumina.Domain.Common.Primitives; using NSubstitute; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -35,6 +36,7 @@ public class CheckInitializationQueryHandlerTests public CheckInitializationQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); @@ -47,30 +49,30 @@ public class CheckInitializationQueryHandlerTests { // Arrange List users = _userEntityFixture.CreateMany(); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(users.AsEnumerable())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); // Act InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsInitialized); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] public async Task HandleAsync_WhenNoUsersExist_ShouldReturnNotInitialized() { // Arrange - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(Enumerable.Empty())); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsInitialized); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -78,7 +80,7 @@ public class CheckInitializationQueryHandlerTests { // Arrange Error error = Error.Failure("Database.Error", "Failed to retrieve users"); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -86,6 +88,6 @@ public class CheckInitializationQueryHandlerTests // Assert Assert.False(result.IsInitialized); - await _mockUserRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockUserRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } } 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 new file mode 100644 index 00000000..75b29816 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandlerTests.cs @@ -0,0 +1,532 @@ +#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.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddAlbumCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly AddAlbumCommandHandler _sut; + private readonly Guid _userId; + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddAlbumCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockPathService = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stubs: the library exists and the track paths are inside its content locations. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stub: updating the artist aggregate succeeds. + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + // Default stub: the persisted album can be read back by its Id. + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_albumEntityFixture.Create(id: callInfo.Arg(), includeTracks: false))); + + _sut = new AddAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.AlbumTitleCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumTitleCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid()); + StubExistingArtist(artist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [], tracks: [_addTrackCommandFixture.Create(contributors: [])]); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingArtistDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheArtistAlreadyHasTheAlbum_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity existingAlbum = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [existingAlbum], includeContributors: false); + StubExistingArtist(artist); + AddAlbumCommand command = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheArtistAlreadyHasTheAlbum, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryUpdateFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheAlbum() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedAlbumCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(_artistEntityFixture.Create(id: artistId, libraryId: libraryId)); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldPersistTheAlbumAndReturnItsResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid existingAlbumId = Guid.NewGuid(); + AlbumEntity existingAlbum = _albumEntityFixture.Create(id: existingAlbumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + ArtistEntity existingArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [existingAlbum], includeContributors: false); + StubExistingArtist(existingArtist); + AddAlbumCommand command = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + ArtistEntity? updatedArtist = null; + AlbumEntity? persistedAlbum = null; + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + return Result.Updated; + }); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + persistedAlbum = _albumEntityFixture.Create(id: callInfo.Arg(), artistId: artistId, libraryId: libraryId, includeTracks: false); + return Result.From(persistedAlbum); + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(updatedArtist); + Assert.NotNull(persistedAlbum); + Assert.Equal(persistedAlbum!.Id, result.Value.Id); + Assert.Equal(persistedAlbum.ArtistId, result.Value.ArtistId); + Assert.Equal(persistedAlbum.LibraryId, result.Value.LibraryId); + Assert.Contains(updatedArtist!.Albums, album => album.Id == persistedAlbum.Id); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Stubs the artist repository so that the artist read returns . + /// + /// The artist returned by the artist repository. + private void StubExistingArtist(ArtistEntity artist) + { + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + } +} 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 new file mode 100644 index 00000000..e95bc068 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidatorTests.cs @@ -0,0 +1,2727 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +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 ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMetadata: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title, which the not empty rule rejects + public void Validate_WhenTitleIsEmpty_ShouldHaveValidationError(string title) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseTypeIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenReleaseTypeIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenReleaseTypeIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenReleaseStatusIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenReleaseStatusIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenReleaseStatusIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Theory] + [InlineData(0)] // zero is not a valid total discs value + [InlineData(-1)] // a negative total discs value is not valid + public void Validate_WhenTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalDiscsIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalDiscsIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid total tracks value + [InlineData(-1)] // a negative total tracks value is not valid + public void Validate_WhenTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalTracksIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalTracksIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenMediaFormatIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(mediaFormat: (MusicMediaFormat)999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenMediaFormatIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenMediaFormatIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(mediaFormat: MusicMediaFormat.CD); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenCatalogNumberExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCatalogNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCatalogNumberIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenBarcodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Theory] + [InlineData("123")] // too short to be a barcode + [InlineData("abcdefghijkl")] // not numeric + [InlineData("12345678901234")] // too long to be a barcode + public void Validate_WhenBarcodeHasInvalidFormat_ShouldHaveValidationError(string barcode) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: barcode); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Theory] + [InlineData("123456789012")] // 12 digit barcode + [InlineData("1234567890123")] // 13 digit barcode + public void Validate_WhenBarcodeIsValid_ShouldNotHaveValidationError(string barcode) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(barcode: barcode); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Fact] + public void Validate_WhenBarcodeIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMusicBrainzReleaseIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzReleaseGroupIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(musicBrainzReleaseGroupId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzReleaseArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(musicBrainzReleaseArtistId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzIdsAreNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create( + musicBrainzReleaseId: Guid.NewGuid(), + musicBrainzReleaseGroupId: Guid.NewGuid(), + musicBrainzReleaseArtistId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeRatings: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(includeValue: false, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingMaxValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, includeMaxValue: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTracksIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(includeTracks: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TracksListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackPathIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includePath: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty path + [InlineData(" ")] // whitespace path, which the not empty rule rejects + public void Validate_WhenTrackPathIsEmpty_ShouldHaveValidationError(string path) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: path)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".flac")]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2000) + ".flac")]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeMetadata: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeTrackNumber: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid track number + [InlineData(-1)] // a negative track number is not valid + public void Validate_WhenTrackNumberIsNotPositive_ShouldHaveValidationError(int trackNumber) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: trackNumber)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: 7)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid disc number + [InlineData(-1)] // a negative disc number is not valid + public void Validate_WhenDiscNumberIsNotPositive_ShouldHaveValidationError(int discNumber) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: discNumber)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: 1)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(51))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenScriptIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(50))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenKeyIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: (MusicKey)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenKeyIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: MusicKey.CMajor)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Theory] + [InlineData(0)] // zero is not a valid tempo + [InlineData(-1)] // a negative tempo is not valid + public void Validate_WhenBpmIsNotPositive_ShouldHaveValidationError(int bpm) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: bpm)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: 120)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWorkIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMoodNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(includeValue: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsrcValueIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "GBUM71029604")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeContributors: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeRatings: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenTrackRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenTrackRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid(), musicBrainzTrackId: Guid.NewGuid(), musicBrainzWorkId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + AddAlbumCommand command = _addAlbumCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs new file mode 100644 index 00000000..927ca97b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandlerTests.cs @@ -0,0 +1,394 @@ +#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.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteAlbumCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly DeleteAlbumCommandHandler _sut; + private readonly Guid _userId; + private readonly DeleteAlbumCommandFixture _deleteAlbumCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteAlbumCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist update succeeds and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new DeleteAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenAlbumExists_ShouldRemoveAlbumFromArtistAndReturnDeleted() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid()); + StubExistingArtist(artist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + await _mockArtistRepository.Received(1).UpdateAsync( + Arg.Is(updatedArtist => + updatedArtist.Id == artistId && + updatedArtist.Albums.Count == 1 && + updatedArtist.Albums.All(album => album.Id != albumId)), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Music.AlbumIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + ArtistEntity artist = CreateArtistWithAlbums(Guid.NewGuid(), artistId, albumId, Guid.NewGuid()); + StubExistingArtist(artist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, Guid.NewGuid(), Guid.NewGuid())); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + AlbumEntity firstAlbum = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + AlbumEntity secondAlbum = _albumEntityFixture.Create(id: Guid.NewGuid(), artistId: artistId, libraryId: libraryId, includeTracks: false); + // An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity. + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [firstAlbum, secondAlbum]); + StubExistingArtist(artist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRemovingTheLastAlbumOfTheArtistFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + // The artist owns a single album, which the aggregate forbids removing. + ArtistEntity artist = CreateArtistWithAlbums(libraryId, artistId, albumId); + StubExistingArtist(artist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + Guid albumId = Guid.Parse(command.AlbumId!); + StubExistingArtist(CreateArtistWithAlbums(libraryId, artistId, albumId, Guid.NewGuid())); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + + /// + /// Creates an artist that owns the provided albums. + /// + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + /// The Ids of the albums the artist owns. + /// The created artist entity. + private ArtistEntity CreateArtistWithAlbums(Guid libraryId, Guid artistId, params Guid[] albumIds) + { + List albums = [.. albumIds.Select(albumId => _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true))]; + return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: albums, includeContributors: true); + } + + /// + /// Stubs the artist repository so that the artist read returns . + /// + /// The artist returned by the artist repository. + private void StubExistingArtist(ArtistEntity artist) + { + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidatorTests.cs new file mode 100644 index 00000000..6cb7ab58 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteAlbumCommandValidatorTests +{ + private readonly DeleteAlbumCommandFixture _deleteAlbumCommandFixture = new(); + private readonly DeleteAlbumCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + DeleteAlbumCommand command = _deleteAlbumCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} 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 new file mode 100644 index 00000000..8b335b56 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandlerTests.cs @@ -0,0 +1,528 @@ +#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.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +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.Albums.Commands.UpdateAlbum; +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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly UpdateAlbumCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: the library exists. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stub: updating the artist aggregate succeeds. + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + // Default stub: the persisted album can be read back by its Id. + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_albumEntityFixture.Create(id: callInfo.Arg(), includeTracks: false))); + + _sut = new UpdateAlbumCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.AlbumTitleCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumTitleCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid()); + StubExistingArtist(artist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: Guid.NewGuid().ToString()); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString(), contributors: []); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingArtistDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [album]); + StubExistingArtist(artist); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + libraryId: libraryId.ToString(), + artistId: artistId.ToString(), + albumId: albumId.ToString(), + metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryUpdateFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedAlbumCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldUpdateTheAlbumAndReturnItsResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + StubExistingArtist(CreateExistingArtist(libraryId, artistId, albumId)); + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + ArtistEntity? updatedArtist = null; + AlbumEntity? persistedAlbum = null; + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + return Result.Updated; + }); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + persistedAlbum = _albumEntityFixture.Create(id: callInfo.Arg(), artistId: artistId, libraryId: libraryId, includeTracks: false); + return Result.From(persistedAlbum); + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(updatedArtist); + Assert.NotNull(persistedAlbum); + Assert.Equal(albumId, result.Value.Id); + Assert.Equal(artistId, result.Value.ArtistId); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Contains(updatedArtist!.Albums, album => album.Id == albumId); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Creates an existing artist that owns a single album, which belongs to the provided library. + /// + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + /// The Id of the album the artist owns. + /// The created artist entity. + private ArtistEntity CreateExistingArtist(Guid libraryId, Guid artistId, Guid albumId) + { + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true); + return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [album], includeContributors: true); + } + + /// + /// Stubs the artist repository so that the artist read returns . + /// + /// The artist returned by the artist repository. + private void StubExistingArtist(ArtistEntity artist) + { + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + } +} 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 new file mode 100644 index 00000000..490c05bc --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidatorTests.cs @@ -0,0 +1,1398 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumCommandValidatorTests +{ + private readonly UpdateAlbumCommandFixture _updateAlbumCommandFixture = new(); + private readonly UpdateAlbumCommandValidator _validator = new(); + private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMetadata: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title, which the not empty rule rejects + public void Validate_WhenTitleIsEmpty_ShouldHaveValidationError(string title) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseTypeIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenReleaseTypeIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenReleaseTypeIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenReleaseStatusIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenReleaseStatusIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenReleaseStatusIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Theory] + [InlineData(0)] // zero is not a valid total discs value + [InlineData(-1)] // a negative total discs value is not valid + public void Validate_WhenTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalDiscsIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalDiscsIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid total tracks value + [InlineData(-1)] // a negative total tracks value is not valid + public void Validate_WhenTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalTracksIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTotalTracksIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenMediaFormatIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(mediaFormat: (MusicMediaFormat)999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenMediaFormatIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenMediaFormatIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(mediaFormat: MusicMediaFormat.CD); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenCatalogNumberExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCatalogNumberIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCatalogNumberIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenBarcodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(barcode: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Theory] + [InlineData("123")] // too short to be a barcode + [InlineData("abcdefghijkl")] // not numeric + [InlineData("12345678901234")] // too long to be a barcode + public void Validate_WhenBarcodeHasInvalidFormat_ShouldHaveValidationError(string barcode) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(barcode: barcode); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Theory] + [InlineData("123456789012")] // 12 digit barcode + [InlineData("1234567890123")] // 13 digit barcode + public void Validate_WhenBarcodeIsValid_ShouldNotHaveValidationError(string barcode) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(barcode: barcode); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Fact] + public void Validate_WhenBarcodeIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMusicBrainzReleaseIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzReleaseGroupIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(musicBrainzReleaseGroupId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzReleaseArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(musicBrainzReleaseArtistId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzIdsAreNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeMediaFormat: false, includeBarcode: false, includeCatalogNumber: false, includeMusicBrainzReleaseId: false, includeMusicBrainzReleaseGroupId: false, includeMusicBrainzReleaseArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create( + musicBrainzReleaseId: Guid.NewGuid(), + musicBrainzReleaseGroupId: Guid.NewGuid(), + musicBrainzReleaseArtistId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(includeRatings: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(includeValue: false, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingMaxValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, includeMaxValue: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(20)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + UpdateAlbumCommand command = _updateAlbumCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandlerTests.cs new file mode 100644 index 00000000..32e9b1a1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandlerTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetAlbumQueryHandler _sut; + private readonly Guid _userId; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly GetAlbumQueryFixture _getAlbumQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAlbumQueryHandlerTests() + { + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetAlbumQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenAlbumExists_ShouldReturnMappedAlbumResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: true, includeMetadata: true); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(albumId, result.Value.Id); + Assert.Equal(artistId, result.Value.ArtistId); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Equal(album.Title, result.Value.Metadata.Title); + Assert.NotNull(result.Value.Tracks); + Assert.Equal(album.Tracks.Count, result.Value.Tracks!.Count); + await _mockAlbumRepository.Received(1).GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the album exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the album exists under another artist. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.AlbumIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumIdCannotBeEmpty, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidatorTests.cs new file mode 100644 index 00000000..dfc95f02 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumQueryValidatorTests +{ + private readonly GetAlbumQueryFixture _getAlbumQueryFixture = new(); + private readonly GetAlbumQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetAlbumQuery query = _getAlbumQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandlerTests.cs new file mode 100644 index 00000000..7d50b037 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandlerTests.cs @@ -0,0 +1,252 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetAlbumTracksQueryHandler _sut; + private readonly Guid _userId; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly GetAlbumTracksQueryFixture _getAlbumTracksQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksQueryHandlerTests() + { + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetAlbumTracksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenAlbumExists_ShouldReturnMappedTracks() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + List tracks = _trackEntityFixture.CreateMany(2); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(Result.From>(tracks)); + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(tracks.Count, result.Value.Count); + Assert.Equal(tracks[0].Id, result.Value[0].Id); + Assert.Equal(tracks[1].Id, result.Value[1].Id); + await _mockTrackRepository.Received(1).GetByAlbumIdAsync(albumId, Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutReadingTracks() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the album exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the album exists under another artist. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetByAlbumIdAsync(albumId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.AlbumIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumIdCannotBeEmpty, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByAlbumIdAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidatorTests.cs new file mode 100644 index 00000000..0f54fe27 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksQueryValidatorTests +{ + private readonly GetAlbumTracksQueryFixture _getAlbumTracksQueryFixture = new(); + private readonly GetAlbumTracksQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetAlbumTracksQuery query = _getAlbumTracksQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandlerTests.cs new file mode 100644 index 00000000..8a4d4a00 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandlerTests.cs @@ -0,0 +1,287 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetAlbumTracksLiteQueryHandler _sut; + private readonly Guid _userId; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackLiteRowFixture _trackLiteRowFixture = new(); + private readonly GetAlbumTracksLiteQueryFixture _getAlbumTracksLiteQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksLiteQueryHandlerTests() + { + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetAlbumTracksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenAlbumExists_ShouldReturnMappedPaginatedTrackLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + List trackLiteRows = _trackLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedTracks = _paginatedResultDtoFixture.Create(data: trackLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetTracksLiteByAlbumIdAsync(albumId, Arg.Any(), Arg.Any()) + .Returns(Result.From(paginatedTracks)); + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(trackLiteRows.Count, result.Value.Data.Count); + Assert.Equal(trackLiteRows[0].Id, result.Value.Data[0].Id); + Assert.Equal(trackLiteRows[0].Title, result.Value.Data[0].Title); + Assert.Equal(trackLiteRows[0].TrackNumber, result.Value.Data[0].TrackNumber); + Assert.Equal(paginatedTracks.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedTracks.PerPage, result.Value.PerPage); + Assert.Equal(paginatedTracks.Count, result.Value.Count); + Assert.Equal(paginatedTracks.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldForwardTheAlbumIdAndPaginationToTheRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + PaginatedResultDto paginatedTracks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetTracksLiteByAlbumIdAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(paginatedTracks)); + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockTrackRepository.Received(1).GetTracksLiteByAlbumIdAsync( + albumId, + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResultWithoutReadingTracks() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFoundError() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + _mockAlbumRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the album exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the album exists under another artist. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(album)); + _mockTrackRepository.GetTracksLiteByAlbumIdAsync(albumId, Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.AlbumIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumIdCannotBeEmpty, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetTracksLiteByAlbumIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidatorTests.cs new file mode 100644 index 00000000..2532021e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidatorTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteQueryValidatorTests +{ + private readonly GetAlbumTracksLiteQueryFixture _getAlbumTracksLiteQueryFixture = new(); + private readonly GetAlbumTracksLiteQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetAlbumTracksLiteQuery query = _getAlbumTracksLiteQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} 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 new file mode 100644 index 00000000..3d13c57e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandlerTests.cs @@ -0,0 +1,391 @@ +#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.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.Albums.Commands.AddAlbum; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly AddArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly AddArtistCommandFixture _addArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockPathService = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stubs: the library exists and the track paths are inside its content locations. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stubs: inserting the artist succeeds and the persisted artist can be read back by its Id. + _mockArtistRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_artistEntityFixture.Create(id: callInfo.Arg(), includeAlbums: false, includeContributors: false))); + + _sut = new AddArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Music.ArtistNameCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + // A single content location makes the path check deterministic, so it can be asserted to have run exactly once per track path. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(contentLocations: ["/music"]))); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + _mockPathService.Received(1).IsPathWithin(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + AddAlbumCommand album = _addAlbumCommandFixture.Create(contributors: [], tracks: [_addTrackCommandFixture.Create(contributors: [])]); + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [], albums: [album]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: string.Empty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryInsertFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockArtistRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheArtist() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldPersistTheArtistAndReturnItsResponse() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + ArtistEntity? insertedArtist = null; + _mockArtistRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + insertedArtist = callInfo.Arg(); + return Result.Created; + }); + ArtistEntity? persistedArtist = null; + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + persistedArtist = _artistEntityFixture.Create(id: callInfo.Arg(), includeAlbums: false, includeContributors: false); + return Result.From(persistedArtist); + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(insertedArtist); + Assert.NotNull(persistedArtist); + Assert.Equal(insertedArtist!.Id, persistedArtist!.Id); + Assert.Equal(persistedArtist.Id, result.Value.Id); + Assert.Equal(persistedArtist.Name, result.Value.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 new file mode 100644 index 00000000..b81d44b5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidatorTests.cs @@ -0,0 +1,2814 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +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 ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name, which the not empty rule rejects + public void Validate_WhenNameIsEmpty_ShouldHaveValidationError(string name) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: name); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: new Faker().Random.String2(256)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(name: new Faker().Random.String2(255)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(website: new Faker().Random.String2(2049)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeWebsite: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(website: new Faker().Internet.Url()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(musicBrainzArtistId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeMusicBrainzArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(musicBrainzArtistId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(includeAlbums: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMetadata: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title, which the not empty rule rejects + public void Validate_WhenAlbumTitleIsEmpty_ShouldHaveValidationError(string title) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Theory] + [InlineData(0)] // zero is not a valid total discs value + [InlineData(-1)] // a negative total discs value is not valid + public void Validate_WhenAlbumTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalDiscsIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalDiscsIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: 2))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid total tracks value + [InlineData(-1)] // a negative total tracks value is not valid + public void Validate_WhenAlbumTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalTracksIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalTracksIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: 10))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenAlbumGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: (MusicMediaFormat)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: MusicMediaFormat.CD)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumBarcodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: string.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Theory] + [InlineData("123")] // too short to be a barcode + [InlineData("abcdefghijkl")] // not numeric + [InlineData("12345678901234")] // too long to be a barcode + public void Validate_WhenAlbumBarcodeHasInvalidFormat_ShouldHaveValidationError(string barcode) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Theory] + [InlineData("123456789012")] // 12 digit barcode + [InlineData("1234567890123")] // 13 digit barcode + public void Validate_WhenAlbumBarcodeIsValid_ShouldNotHaveValidationError(string barcode) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseGroupIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseGroupId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseArtistId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeContributors: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeRatings: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenAlbumRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(includeValue: false, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenAlbumRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingMaxValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, includeMaxValue: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumTracksIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeTracks: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TracksListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackPathIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includePath: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty path + [InlineData(" ")] // whitespace path, which the not empty rule rejects + public void Validate_WhenTrackPathIsEmpty_ShouldHaveValidationError(string path) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: path)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2000) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeMetadata: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + 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)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + 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)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeTrackNumber: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid track number + [InlineData(-1)] // a negative track number is not valid + public void Validate_WhenTrackNumberIsNotPositive_ShouldHaveValidationError(int trackNumber) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: trackNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid disc number + [InlineData(-1)] // a negative disc number is not valid + public void Validate_WhenDiscNumberIsNotPositive_ShouldHaveValidationError(int discNumber) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: discNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(51))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackKeyIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: (MusicKey)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Theory] + [InlineData(0)] // zero is not a valid tempo + [InlineData(-1)] // a negative tempo is not valid + public void Validate_WhenTrackBpmIsNotPositive_ShouldHaveValidationError(int bpm) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: bpm)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(includeValue: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeContributors: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeRatings: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenTrackRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenTrackRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.NewGuid(), musicBrainzReleaseGroupId: Guid.NewGuid(), musicBrainzReleaseArtistId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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())])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: 7)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: 1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackScriptIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(50))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenTrackKeyIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: MusicKey.CMajor)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: 120)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackWorkIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "GBUM71029604")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + AddArtistCommand command = _addArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs new file mode 100644 index 00000000..19f1198a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandlerTests.cs @@ -0,0 +1,306 @@ +#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.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly DeleteArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly DeleteArtistCommandFixture _deleteArtistCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the library exists, the artist deletion succeeds and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new DeleteArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldDeleteArtistAndReturnDeleted() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteArtistFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockArtistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + Guid artistId = Guid.Parse(command.ArtistId!); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).DeleteByIdAsync(artistId, Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidatorTests.cs new file mode 100644 index 00000000..b0c640a1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistCommandValidatorTests +{ + private readonly DeleteArtistCommandFixture _deleteArtistCommandFixture = new(); + private readonly DeleteArtistCommandValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + DeleteArtistCommand command = _deleteArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} 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 new file mode 100644 index 00000000..35ab36e6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandlerTests.cs @@ -0,0 +1,572 @@ +#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.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly UpdateArtistCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateArtistCommandFixture _updateArtistCommandFixture = new(); + private readonly AddAlbumCommandFixture _addAlbumCommandFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockPathService = Substitute.For(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stubs: the validator passes, the current user is authenticated and the library ownership policy allows access. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stubs: the library exists and the track paths are inside its content locations. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stub: updating the artist aggregate succeeds. + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new UpdateArtistCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistNameCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid()); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString()); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutUpdating() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + // A single content location makes the path check deterministic, so it can be asserted to have run exactly once per track path. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(contentLocations: ["/music"]))); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + _mockPathService.Received(1).IsPathWithin(Arg.Any(), Arg.Any()); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + AddTrackCommand track = _addTrackCommandFixture.Create(contributors: []); + AddAlbumCommand album = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId, contributors: [], tracks: [track]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), contributors: [], albums: [album]); + ArtistEntity persistedArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)], includeContributors: false); + StubArtistReads(existingArtist, persistedArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenExistingArtistDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false); + ArtistEntity existingArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: string.Empty, albums: [album]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + 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); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRemovingTheLastAlbumOfTheArtistFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + // An empty albums list makes the mapping treat the only existing album as stale and remove it, which the aggregate forbids. + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albums: [], contributors: []); + StubArtistReads(existingArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryUpdateFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheArtist() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist, error: ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + StubArtistReads(existingArtist, persistedArtist: null, hasPersistedArtist: true); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldUpdateTheArtistAndReturnItsResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + ArtistEntity existingArtist = CreateExistingArtist(libraryId, artistId, albumId); + AddTrackCommand track = _addTrackCommandFixture.Create(); + AddAlbumCommand album = _addAlbumCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId, tracks: [track]); + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albums: [album]); + ArtistEntity persistedArtist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false)], includeContributors: false); + ArtistEntity? updatedArtist = null; + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + return Result.Updated; + }); + StubArtistReads(existingArtist, persistedArtist); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(updatedArtist); + Assert.Equal(artistId, result.Value.Id); + Assert.Equal(persistedArtist.Name, result.Value.Name); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Creates an existing artist that owns a single album, which belongs to the provided library. + /// + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + /// The Id of the album the artist owns. + /// The created artist entity. + private ArtistEntity CreateExistingArtist(Guid libraryId, Guid artistId, Guid albumId) + { + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: true); + return _artistEntityFixture.Create(id: artistId, libraryId: libraryId, albums: [album], includeContributors: true); + } + + /// + /// Stubs the artist repository so that the initial artist read, and optionally the persisted artist read, return the provided entities. + /// + /// The artist returned by the initial read. + /// Optional. The artist returned by the persisted read. When not provided, is returned again. + /// Optional. The error returned by the persisted read, when it must fail. + /// Whether the persisted read returns a value, which can be . + private void StubArtistReads(ArtistEntity artist, ArtistEntity? persistedArtist = null, Error? error = null, bool hasPersistedArtist = false) + { + Queue> readResults = new(); + readResults.Enqueue(Result.From(artist)); + if (error is not null) + readResults.Enqueue(error); + else if (hasPersistedArtist) + readResults.Enqueue(Result.From(persistedArtist)); + else + readResults.Enqueue(Result.From(persistedArtist ?? artist)); + + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(_ => readResults.Dequeue()); + } +} 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 new file mode 100644 index 00000000..6db619ee --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidatorTests.cs @@ -0,0 +1,2896 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +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.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +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 ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name, which the not empty rule rejects + public void Validate_WhenNameIsEmpty_ShouldHaveValidationError(string name) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: name); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: new Faker().Random.String2(256)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(name: new Faker().Random.String2(255)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.ArtistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(website: new Faker().Random.String2(2049)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeWebsite: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenWebsiteIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(website: new Faker().Internet.Url()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistWebsiteMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(musicBrainzArtistId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeMusicBrainzArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(musicBrainzArtistId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(includeAlbums: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(albumId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeAlbumId: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(albumId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeMetadata: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty title + [InlineData(" ")] // whitespace title, which the not empty rule rejects + public void Validate_WhenAlbumTitleIsEmpty_ShouldHaveValidationError(string title) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: title))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(title: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalTitle: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(2001)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeDescription: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: (MusicReleaseType)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseType: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseTypeIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseType: MusicReleaseType.Album))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseType); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: (MusicReleaseStatus)999))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseStatus: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Fact] + public void Validate_WhenAlbumReleaseStatusIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseStatus: MusicReleaseStatus.Official))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicReleaseStatus); + } + + [Theory] + [InlineData(0)] // zero is not a valid total discs value + [InlineData(-1)] // a negative total discs value is not valid + public void Validate_WhenAlbumTotalDiscsIsNotPositive_ShouldHaveValidationError(int totalDiscs) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalDiscs: totalDiscs))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalDiscsIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalDiscs: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalDiscsMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid total tracks value + [InlineData(-1)] // a negative total tracks value is not valid + public void Validate_WhenAlbumTotalTracksIsNotPositive_ShouldHaveValidationError(int totalTracks) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(totalTracks: totalTracks))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumTotalTracksIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTotalTracks: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TotalTracksMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenAlbumReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeReleaseInfo: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenAlbumReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenAlbumGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeGenres: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeTags: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))]))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(includeOriginalLanguage: false))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: (MusicMediaFormat)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumMediaFormatIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(mediaFormat: MusicMediaFormat.CD)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicMediaFormat); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(51))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumBarcodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: string.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Theory] + [InlineData("123")] // too short to be a barcode + [InlineData("abcdefghijkl")] // not numeric + [InlineData("12345678901234")] // too long to be a barcode + public void Validate_WhenAlbumBarcodeHasInvalidFormat_ShouldHaveValidationError(string barcode) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Theory] + [InlineData("123456789012")] // 12 digit barcode + [InlineData("1234567890123")] // 13 digit barcode + public void Validate_WhenAlbumBarcodeIsValid_ShouldNotHaveValidationError(string barcode) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(barcode: barcode)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.InvalidFormatForBarcode); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BarcodeValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseGroupIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseGroupId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzReleaseArtistIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseArtistId: Guid.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(musicBrainzReleaseId: Guid.NewGuid(), musicBrainzReleaseGroupId: Guid.NewGuid(), musicBrainzReleaseArtistId: Guid.NewGuid())]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenAlbumContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeContributors: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenAlbumContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenAlbumRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeRatings: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenAlbumRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(includeValue: false, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenAlbumRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingMaxValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, includeMaxValue: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumTracksIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(includeTracks: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TracksListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create()])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackId: Guid.NewGuid())])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includePath: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Theory] + [InlineData("")] // empty path + [InlineData(" ")] // whitespace path, which the not empty rule rejects + public void Validate_WhenTrackPathIsEmpty_ShouldHaveValidationError(string path) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: path)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackPathExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackPathIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2000) + ".flac")])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeMetadata: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTrackReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenTrackReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenTrackGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + 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)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + 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)]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeTrackNumber: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid track number + [InlineData(-1)] // a negative track number is not valid + public void Validate_WhenTrackNumberIsNotPositive_ShouldHaveValidationError(int trackNumber) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: trackNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid disc number + [InlineData(-1)] // a negative disc number is not valid + public void Validate_WhenDiscNumberIsNotPositive_ShouldHaveValidationError(int discNumber) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: discNumber)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(51))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackKeyIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: (MusicKey)999)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Theory] + [InlineData(0)] // zero is not a valid tempo + [InlineData(-1)] // a negative tempo is not valid + public void Validate_WhenTrackBpmIsNotPositive_ShouldHaveValidationError(int bpm) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: bpm)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(256))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(includeValue: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeContributors: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTrackContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(includeRatings: false)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenTrackRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenTrackRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenAlbumOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(metadata: _albumMetadataDtoFixture.Create(description: new Faker().Random.String2(1500)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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)))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenAlbumCatalogNumberIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(catalogNumber: new Faker().Random.String2(50))]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.CatalogNumberMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))]))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false)))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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))))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + 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())])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(trackNumber: 7)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(discNumber: 1)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTrackScriptIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(script: new Faker().Random.String2(50))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenTrackKeyIsDefined_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(key: MusicKey.CMajor)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(bpm: 120)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackWorkIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(work: new Faker().Random.String2(255))])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTrackMoodNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIsrcValueIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "GBUM71029604")])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + 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)])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenTrackRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenTrackRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(albums: [_addAlbumCommandFixture.Create(tracks: [_addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)])])]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + UpdateArtistCommand command = _updateArtistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} 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 new file mode 100644 index 00000000..51d67bb7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandlerTests.cs @@ -0,0 +1,202 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly GetArtistQueryFixture _getArtistQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldReturnMappedArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: true, includeContributors: true); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + 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.Website, result.Value.Website); + Assert.NotNull(result.Value.Albums); + Assert.Equal(artist.Albums.Count, result.Value.Albums!.Count); + Assert.NotNull(result.Value.Contributors); + Assert.Equal(artist.Contributors.Count, result.Value.Contributors!.Count); + await _mockArtistRepository.Received(1).GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutEvaluatingThePolicy() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid()); + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId); + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidatorTests.cs new file mode 100644 index 00000000..edd39458 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistQueryValidatorTests +{ + private readonly GetArtistQueryFixture _getArtistQueryFixture = new(); + private readonly GetArtistQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistQuery query = _getArtistQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandlerTests.cs new file mode 100644 index 00000000..0a0281eb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandlerTests.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistAlbumsQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly GetArtistAlbumsQueryFixture _getArtistAlbumsQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistAlbumsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldReturnMappedAlbums() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + List albums = _albumEntityFixture.CreateMany(2); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(Result.From>(albums)); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(albums.Count, result.Value.Count); + Assert.Equal(albums[0].Id, result.Value[0].Id); + Assert.Equal(albums[1].Id, result.Value[1].Id); + await _mockAlbumRepository.Received(1).GetByArtistIdAsync(artistId, Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutReadingAlbums() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetByArtistIdAsync(artistId, Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetByArtistIdAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidatorTests.cs new file mode 100644 index 00000000..2f7316d5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsQueryValidatorTests +{ + private readonly GetArtistAlbumsQueryFixture _getArtistAlbumsQueryFixture = new(); + private readonly GetArtistAlbumsQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistAlbumsQuery query = _getArtistAlbumsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandlerTests.cs new file mode 100644 index 00000000..d97d5385 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandlerTests.cs @@ -0,0 +1,262 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistAlbumsLiteQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumLiteRowFixture _albumLiteRowFixture = new(); + private readonly GetArtistAlbumsLiteQueryFixture _getArtistAlbumsLiteQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsLiteQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockAlbumRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistAlbumsLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenArtistExists_ShouldReturnMappedPaginatedAlbumLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + List albumLiteRows = _albumLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedAlbums = _paginatedResultDtoFixture.Create(data: albumLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, Arg.Any(), Arg.Any()) + .Returns(Result.From(paginatedAlbums)); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(albumLiteRows.Count, result.Value.Data.Count); + Assert.Equal(albumLiteRows[0].Id, result.Value.Data[0].Id); + Assert.Equal(albumLiteRows[0].Title, result.Value.Data[0].Title); + Assert.Equal(albumLiteRows[0].TotalTracks, result.Value.Data[0].TotalTracks); + Assert.Equal(paginatedAlbums.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedAlbums.PerPage, result.Value.PerPage); + Assert.Equal(paginatedAlbums.Count, result.Value.Count); + Assert.Equal(paginatedAlbums.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldForwardTheArtistIdAndPaginationToTheRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + PaginatedResultDto paginatedAlbums = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(paginatedAlbums)); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockAlbumRepository.Received(1).GetAlbumsLiteByArtistIdAsync( + artistId, + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && + paginationData.PerPage == query.PaginationData.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutReadingAlbums() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingThePolicy() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), includeAlbums: false, includeContributors: false); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAlbumRepository.GetAlbumsLiteByArtistIdAsync(artistId, Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ArtistIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAlbumRepository.DidNotReceive().GetAlbumsLiteByArtistIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidatorTests.cs new file mode 100644 index 00000000..7b52c0d9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidatorTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteQueryValidatorTests +{ + private readonly GetArtistAlbumsLiteQueryFixture _getArtistAlbumsLiteQueryFixture = new(); + private readonly GetArtistAlbumsLiteQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistAlbumsLiteQuery query = _getArtistAlbumsLiteQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandlerTests.cs new file mode 100644 index 00000000..35b0e318 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandlerTests.cs @@ -0,0 +1,255 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistsQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly GetArtistsQueryFixture _getArtistsQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistsQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + List artistEntities = _artistEntityFixture.CreateMany(2); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: artistEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artistEntities.Count, result.Value.Data.Count); + Assert.Equal(paginatedArtists.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedArtists.PerPage, result.Value.PerPage); + Assert.Equal(paginatedArtists.Count, result.Value.Count); + Assert.Equal(paginatedArtists.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Data); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Errors.Library.FilterMustIncludeLibraryId); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterPaginationAndSearchTerm() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString(), searchTerm: "Queen"); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockArtistRepository.Received(1).GetAllAsync( + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + shouldTrackEntities: false, + cancellationToken: Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString(), includePaginationData: false, searchTerm: "Queen"); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + shouldTrackEntities: false, + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockArtistRepository.Received(1).GetAllAsync( + Arg.Is(paginationData => paginationData == null), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId.ToString()); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidatorTests.cs new file mode 100644 index 00000000..a9f6b450 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsQueryValidatorTests +{ + private readonly GetArtistsQueryFixture _getArtistsQueryFixture = new(); + private readonly GetArtistsQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistsQuery query = _getArtistsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandlerTests.cs new file mode 100644 index 00000000..1b4f19bb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandlerTests.cs @@ -0,0 +1,250 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetArtistsLiteQueryHandler _sut; + private readonly Guid _userId; + private readonly ArtistLiteRowFixture _artistLiteRowFixture = new(); + private readonly GetArtistsLiteQueryFixture _getArtistsLiteQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsLiteQueryHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access and the validator passes. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetArtistsLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + List artistLiteRows = _artistLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: artistLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artistLiteRows.Count, result.Value.Data.Count); + Assert.Equal(artistLiteRows[0].Id, result.Value.Data[0].Id); + Assert.Equal(artistLiteRows[0].Name, result.Value.Data[0].Name); + Assert.Equal(paginatedArtists.CurrentPage, result.Value.CurrentPage); + Assert.Equal(paginatedArtists.PerPage, result.Value.PerPage); + Assert.Equal(paginatedArtists.Count, result.Value.Count); + Assert.Equal(paginatedArtists.NumberOfPages, result.Value.NumberOfPages); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsEmptyPage_ShouldReturnEmptyPaginatedResponses() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Data); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Errors.Library.FilterMustIncludeLibraryId); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldQueryRepositoryWithMappedFilterPaginationAndSearchTerm() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString(), searchTerm: "Queen"); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockArtistRepository.Received(1).GetAllLiteAsync( + Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + cancellationToken: Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString(), includePaginationData: false, searchTerm: "Queen"); + PaginatedResultDto paginatedArtists = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockArtistRepository.GetAllLiteAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + cancellationToken: Arg.Any()) + .Returns(Result.From(paginatedArtists)); + + // Act + await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + await _mockArtistRepository.Received(1).GetAllLiteAsync( + Arg.Is(paginationData => paginationData == null), + Arg.Any(), + Arg.Any(), + Arg.Is(filter => filter.LibraryId == libraryId && filter.SearchTerm == "Queen"), + cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId.ToString()); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidatorTests.cs new file mode 100644 index 00000000..a2335d28 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidatorTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteQueryValidatorTests +{ + private readonly GetArtistsLiteQueryFixture _getArtistsLiteQueryFixture = new(); + private readonly GetArtistsLiteQueryValidator _validator = new(); + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + GetArtistsLiteQuery query = _getArtistsLiteQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} 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 new file mode 100644 index 00000000..1d398a19 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandlerTests.cs @@ -0,0 +1,548 @@ +#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.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +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.AddTrack; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddTrackCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly Guid _userId; + private readonly AddTrackCommandHandler _sut; + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddTrackCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + // Default stub: the validator passes and the current user is authenticated. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + // Default stub: the library ownership policy allows access. + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: the library exists and the track path is inside its content locations. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => + { + IReadOnlyCollection contributorIds = callInfo.Arg>(); + return Result.From>([.. contributorIds.Select(contributorId => _mediaContributorEntityFixture.Create(id: contributorId, displayName: contributorId.ToString()))]); + }); + // Default stub: updating the artist aggregate succeeds. + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + // Default stub: the persisted track can be read back by its Id. + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_trackEntityFixture.Create(id: callInfo.Arg()))); + _sut = new AddTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.Music.TrackPathCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundWithoutEvaluatingPolicy() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command, libraryId: Guid.NewGuid()); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // The mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserDoesNotOwnTheLibrary_ShouldReturnNotAuthorizedError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + Guid libraryId = Guid.Parse(command.LibraryId!); + ArrangeArtist(command); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExistInTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command, albumId: Guid.NewGuid()); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackPathIsNotWithinLibraryContentLocations_ShouldReturnFailureResult() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + ArrangeArtist(command); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnMediaContributorNotFoundError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + ArrangeArtist(command); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(contributors: []); + ArrangeArtist(command); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command, name: string.Empty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandDomainConversionFails_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + ArrangeArtist(command); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackIsAlreadyInTheAlbum_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + TrackEntity existingTrack = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, includeMetadata: false); + AlbumEntity album = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [existingTrack]; + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: libraryId, includeAlbums: false, includeContributors: false); + artist.Albums = [album]; + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + AddTrackCommand command = _addTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: artistId.ToString(), albumId: albumId.ToString(), trackId: trackId); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryUpdateFails_ShouldReturnFailureResultWithoutSavingChanges() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingTheTrack() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedTrackCannotBeRead_ShouldReturnFailureResult() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.Music.TrackIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenPersistedTrackDoesNotExist_ShouldReturnTrackNotFoundError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + ArrangeArtist(command); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithValidCommand_ShouldPersistTheTrackAndReturnItsResponse() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + Guid albumId = Guid.Parse(command.AlbumId!); + Guid libraryId = Guid.Parse(command.LibraryId!); + ArrangeArtist(command); + ArtistEntity? updatedArtist = null; + TrackEntity? persistedTrack = null; + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + return Result.Updated; + }); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + persistedTrack = _trackEntityFixture.Create(id: callInfo.Arg(), albumId: albumId, libraryId: libraryId); + return Result.From(persistedTrack); + }); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(persistedTrack); + Assert.NotNull(updatedArtist); + Assert.Equal(persistedTrack!.Id, result.Value.Id); + Assert.Equal(persistedTrack.Path, result.Value.Path); + Assert.Equal(persistedTrack.Title, result.Value.Metadata.Title); + Assert.Contains(updatedArtist!.Albums.Single().Tracks, track => track.Id == persistedTrack.Id); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Arranges an existing artist that matches the route identifiers of , together with one album. + /// + /// The command whose route identifiers are used. + /// Optional. The Id of the album contained by the artist, when it must differ from the route album Id. + /// Optional. The Id of the media library the artist belongs to, when it must differ from the route library Id. + /// Optional. The name of the artist. + /// The existing artist entity. + private ArtistEntity ArrangeArtist(AddTrackCommand command, Guid? albumId = null, Guid? libraryId = null, string? name = null) + { + Guid artistId = Guid.Parse(command.ArtistId!); + Guid resolvedLibraryId = libraryId ?? Guid.Parse(command.LibraryId!); + Guid resolvedAlbumId = albumId ?? Guid.Parse(command.AlbumId!); + AlbumEntity album = _albumEntityFixture.Create(id: resolvedAlbumId, artistId: artistId, libraryId: resolvedLibraryId, includeTracks: false, includeMetadata: false); + ArtistEntity artist = _artistEntityFixture.Create(id: artistId, libraryId: resolvedLibraryId, name: name, includeAlbums: false, includeContributors: false); + artist.Albums = [album]; + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + return artist; + } +} 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 new file mode 100644 index 00000000..0c14b1e1 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidatorTests.cs @@ -0,0 +1,1454 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +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.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddTrackCommandValidatorTests +{ + private readonly AddTrackCommandFixture _addTrackCommandFixture = new(); + private readonly AddTrackCommandValidator _validator = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(libraryId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(libraryId: "not-a-library-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(artistId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(artistId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(artistId: "not-an-artist-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeAlbumId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(albumId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(albumId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(albumId: "not-an-album-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includePath: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathIsLongerThan2048Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".flac"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenPathIsAtMost2048Characters_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(path: "/" + new Faker().Random.String2(2000) + ".flac"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeMetadata: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTitleIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseDateAndYearDoNotMatch_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2020))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseDateAndYearMatch_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2021, 1, 1), reReleaseYear: 2021))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2001, reReleaseYear: 2000, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenGenresIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageCodeIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(2)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsNot2CharactersLong_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create( + musicBrainzRecordingId: Guid.NewGuid(), + musicBrainzTrackId: Guid.NewGuid(), + musicBrainzWorkId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeTrackNumber: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid track number + [InlineData(-1)] // a negative track number is not valid + public void Validate_WhenTrackNumberIsNotPositive_ShouldHaveValidationError(int trackNumber) + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(trackNumber: trackNumber); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(trackNumber: 7); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Theory] + [InlineData(0)] // zero is not a valid disc number + [InlineData(-1)] // a negative disc number is not valid + public void Validate_WhenDiscNumberIsNotPositive_ShouldHaveValidationError(int discNumber) + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(discNumber: discNumber); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(discNumber: 1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(script: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenScriptIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(script: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenKeyIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(key: (MusicKey)999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenKeyIsDefined_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(key: MusicKey.CMajor); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Theory] + [InlineData(0)] // zero is not a valid tempo + [InlineData(-1)] // a negative tempo is not valid + public void Validate_WhenBpmIsNotPositive_ShouldHaveValidationError(int bpm) + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(bpm: bpm); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(bpm: 120); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(work: new Faker().Random.String2(256)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWorkIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(work: new Faker().Random.String2(255)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(includeName: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMoodNameIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(includeValue: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsrcValueIsValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: "GBUM71029604")]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsNotDefined_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(includeRatings: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Theory] + [InlineData(0)] // zero is not a valid rating value + [InlineData(-1)] // a negative rating value is not valid + public void Validate_WhenRatingValueIsNotPositive_ShouldHaveValidationError(decimal value) + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: value, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Theory] + [InlineData(0)] // zero is not a valid maximum rating value + [InlineData(-1)] // a negative maximum rating value is not valid + public void Validate_WhenRatingMaxValueIsNotPositive_ShouldHaveValidationError(decimal maxValue) + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: maxValue)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + AddTrackCommand command = _addTrackCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs new file mode 100644 index 00000000..4c37e1db --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandlerTests.cs @@ -0,0 +1,483 @@ +#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.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +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.DeleteTrack; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteTrackCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly DeleteTrackCommandHandler _sut; + private readonly DeleteTrackCommandFixture _deleteTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public DeleteTrackCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtistRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the artist update succeeds and saving changes succeeds. + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(Result.Success); + + _sut = new DeleteTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenTrackExists_ShouldRemoveTrackFromAlbumAndReturnDeleted() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + StubArtistAndLibrary(artist, libraryId); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + await _mockArtistRepository.Received(1).UpdateAsync( + Arg.Is(updatedArtist => + updatedArtist.Id == artistId && + updatedArtist.Albums.Count == 1 && + updatedArtist.Albums[0].Id == albumId && + updatedArtist.Albums[0].Tracks.Count == 0), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldLoadTheArtistWithNavigationPropertiesAndTheLibraryWithoutTracking() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + StubArtistAndLibrary(artist, libraryId); + + // Act + await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + await _mockArtistRepository.Received(1).GetByIdAsync( + artistId, + shouldIncludeNavigationProperties: true, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync( + libraryId, + shouldTrackEntities: false, + cancellationToken: Arg.Any()); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, + Arg.Is(context => context.LibraryId == libraryId), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.Music.TrackIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetArtistFails_ShouldReturnError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (_, Guid artistId, _, _) = GetCommandIds(command); + Error error = Error.Failure(description: "Failed to get artist"); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (_, Guid artistId, _, _) = GetCommandIds(command); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundErrorWithoutEvaluatingThePolicy() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(Guid.NewGuid(), artistId, albumId, trackId); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the artist exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumDoesNotExistInArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, _, Guid trackId) = GetCommandIds(command); + Guid otherAlbumId = Guid.NewGuid(); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, otherAlbumId, trackId); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.AlbumNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackDoesNotExistInAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, _) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, Guid.NewGuid()); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetLibraryFails_ShouldReturnError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + Error error = Error.Failure(description: "Failed to get library"); + _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + _mockArtistRepository.GetByIdAsync(artistId, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDomainConversionFails_ShouldReturnError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + // An empty name is rejected by the artist aggregate invariant, so the repository entity fails to convert to a domain entity. + AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId); + ArtistEntity artist = _artistEntityFixture.Create( + id: artistId, + libraryId: libraryId, + name: string.Empty, + albums: [album], + includeContributors: false, + includeMetadata: false); + StubArtistAndLibrary(artist, libraryId); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.ArtistNameCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateArtistFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + StubArtistAndLibrary(artist, libraryId); + Error error = Error.Failure(description: "Failed to update artist"); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = GetCommandIds(command); + ArtistEntity artist = CreateArtistWithAlbumAndTrack(libraryId, artistId, albumId, trackId); + StubArtistAndLibrary(artist, libraryId); + Error error = Error.Failure(description: "Failed to save changes"); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + + /// + /// Extracts the parsed identifiers carried by . + /// + /// The command whose route identifiers are extracted. + /// The parsed library, artist, album and track identifiers. + private static (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) GetCommandIds(DeleteTrackCommand command) + { + return ( + Guid.Parse(command.LibraryId!), + Guid.Parse(command.ArtistId!), + Guid.Parse(command.AlbumId!), + Guid.Parse(command.TrackId!)); + } + + /// + /// Creates an artist that contains a single album, which in turn contains a single track. + /// + /// The Id of the media library the artist belongs to. + /// The Id of the artist. + /// The Id of the album. + /// The Id of the track. + /// The created artist entity, with its album and track graph. + private ArtistEntity CreateArtistWithAlbumAndTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + AlbumEntity album = CreateAlbumWithTrack(libraryId, artistId, albumId, trackId); + return _artistEntityFixture.Create( + id: artistId, + libraryId: libraryId, + albums: [album], + includeContributors: false, + includeMetadata: false); + } + + /// + /// Creates an album that contains a single track. + /// + /// The Id of the media library the album belongs to. + /// The Id of the artist the album belongs to. + /// The Id of the album. + /// The Id of the track. + /// The created album entity, with its track. + private AlbumEntity CreateAlbumWithTrack(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + TrackEntity track = _trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + return _albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + tracks: [track], + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + } + + /// + /// Stubs the artist and library repositories so that the handler finds the artist and the library. + /// + /// The artist returned by the artist repository. + /// The Id of the media library returned by the library repository. + private void StubArtistAndLibrary(ArtistEntity artist, Guid libraryId) + { + _mockArtistRepository.GetByIdAsync(artist.Id, shouldIncludeNavigationProperties: true, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(artist)); + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId); + _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidatorTests.cs new file mode 100644 index 00000000..722277b4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidatorTests.cs @@ -0,0 +1,122 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteTrackCommandValidatorTests +{ + private readonly DeleteTrackCommandFixture _deleteTrackCommandFixture = new(); + private readonly DeleteTrackCommandValidator _validator = new(); + + [Fact] + public void Validate_WhenIdsAreValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-track-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId) + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(trackId: trackId, includeTrackId: trackId is not null); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOnlyTheArtistIdIsInvalid_ShouldNotReportUnrelatedValidationErrors() + { + // Arrange + DeleteTrackCommand command = _deleteTrackCommandFixture.Create(artistId: "not-an-artist-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } +} 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 new file mode 100644 index 00000000..fe9bb86e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandlerTests.cs @@ -0,0 +1,591 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +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.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +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; +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.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtistRepository _mockArtistRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaContributorRepository _mockMediaContributorRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; + private readonly UpdateTrackCommandHandler _sut; + private readonly Guid _userId; + private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateTrackCommandHandlerTests() + { + _mockArtistRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockMediaContributorRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockPathService = Substitute.For(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated, the library ownership policy allows access, the validator passes, + // the track path is within the library content locations, the artist is updated and the library and contributors exist. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_trackEntityFixture.Create(id: callInfo.ArgAt(0)))); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .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 + })]); + }); + + _sut = new UpdateTrackCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValid_ShouldUpdateTrackAndReturnResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString()); + ArtistEntity? updatedArtist = null; + TrackEntity? updatedTrack = null; + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + updatedTrack = updatedArtist.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId); + return Result.Updated; + }); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(updatedTrack)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(trackId, result.Value.Id); + Assert.Equal(command.Path, result.Value.Path); + Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count); + await _mockArtistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidatorFails_ShouldReturnValidationErrorsWithoutUpdating() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.TrackIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockArtistRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.Music.ArtistNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFoundError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistBelongsToAnotherLibrary_ShouldReturnArtistNotFoundError() + { + // Arrange + Guid routeLibraryId = Guid.NewGuid(); + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid()); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: routeLibraryId.ToString(), artistId: existingArtist.Id.ToString()); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorWithoutUpdating() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumIsNotPartOfTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid _, Guid trackId) = CreateArtistWithTrack(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: Guid.NewGuid().ToString(), trackId: trackId.ToString()); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackIsNotPartOfTheAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid _) = CreateArtistWithTrack(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: Guid.NewGuid().ToString()); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Errors.Library.LibraryNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundErrorWithoutUpdating() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathIsNotWithinLibraryContentLocations_ShouldReturnPathError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create(contentLocations: ["/music/queen"]))); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackPathMustBeWithinLibraryContentLocations, result.FirstError); + _mockPathService.Received(1).IsPathWithin(command.Path!, Arg.Any()); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenNoContributorsAreReferenced_ShouldNotQueryTheContributorRepository() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), contributors: []); + ArtistEntity? updatedArtist = null; + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedArtist = callInfo.Arg(); + return Result.Updated; + }); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(updatedArtist!.Albums.SelectMany(album => album.Tracks).First(track => track.Id == trackId))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Errors.MediaContributor.MediaContributorNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), contributors: [_mediaContributorReferenceDtoFixture.Create()]); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenContributorIdsAreDuplicated_ShouldQueryTheRepositoryWithDistinctIds() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + Guid firstContributorId = Guid.NewGuid(); + Guid secondContributorId = Guid.NewGuid(); + List duplicatedContributors = + [ + _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Vocals), + _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Guitar), + _mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Producer), + _mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Producer) + ]; + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: libraryId.ToString(), artistId: existingArtist.Id.ToString(), albumId: albumId.ToString(), trackId: trackId.ToString(), contributors: duplicatedContributors); + _mockArtistRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(existingArtist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMediaContributorRepository.Received(1).GetByIdsAsync( + Arg.Is>(contributorIds => contributorIds.Count == 2 && contributorIds.Contains(firstContributorId) && contributorIds.Contains(secondContributorId)), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenArtistToDomainEntityConversionFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + 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)]; + 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()) + .Returns(Result.From(existingArtist)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCommandToDomainEntityConversionFails_ShouldReturnFailureResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + AudioMetadataDto invalidMetadata = _audioMetadataDtoFixture.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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + await _mockArtistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockArtistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Errors.Library.LibraryNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReadingThePersistedTrack() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Errors.Library.LibraryNotFound); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPersistedTrackIsNotFound_ShouldReturnTrackNotFoundError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + (ArtistEntity existingArtist, Guid albumId, Guid trackId) = CreateArtistWithTrack(libraryId); + 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()) + .Returns(Result.From(existingArtist)); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + /// + /// Creates an artist entity that owns a single album, which in turn owns a single track, all belonging to . + /// + /// The Id of the media library the artist belongs to. + /// The created artist entity, together with the Ids of its album and track. + private (ArtistEntity artist, Guid albumId, Guid trackId) CreateArtistWithTrack(Guid libraryId) + { + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create( + libraryId: libraryId, + albums: + [ + _albumEntityFixture.Create( + id: albumId, + libraryId: libraryId, + tracks: [_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId)]) + ]); + return (artist, albumId, trackId); + } +} 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 new file mode 100644 index 00000000..5af646ad --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidatorTests.cs @@ -0,0 +1,1771 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Application.UnitTests.Common.Setup; +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.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +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 System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackCommandValidatorTests +{ + private readonly UpdateTrackCommandFixture _updateTrackCommandFixture = new(); + private readonly UpdateTrackCommandValidator _validator = new(); + private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + private readonly MoodDtoFixture _moodDtoFixture = new(); + private readonly IsrcDtoFixture _isrcDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly AudioRatingDtoFixture _audioRatingDtoFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsAnEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeArtistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(artistId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(artistId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(artistId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsAnEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(artistId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(artistId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeAlbumId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(albumId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(albumId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(albumId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsAnEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(albumId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(albumId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeTrackId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackId: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackId: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsAnEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includePath: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPathExceeds2048Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: new Faker().Random.String2(2049)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenPathIs2048Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(path: new Faker().Random.String2(2048)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackPathMustBeMaximum2048CharactersLong); + } + + [Fact] + public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeMetadata: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); + } + + [Fact] + public void Validate_WhenTitleIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: string.Empty)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleIsWhitespace_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: " ")); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(256))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenTitleIs255Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(title: new Faker().Random.String2(255))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(256))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIs255Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(255))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalTitle: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIs2000Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(description: new Faker().Random.String2(2000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeDescription: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeReleaseInfo: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 0, includeReReleaseDate: false, includeReReleaseYear: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 10000, includeReReleaseDate: false, includeReReleaseYear: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, includeReReleaseYear: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, reReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, reReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, reReleaseYear: 2001))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, includeOriginalReleaseYear: false, includeReReleaseDate: false, includeReReleaseYear: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIs50Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeReleaseVersion: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateAndYearMustMatch); + } + + [Fact] + public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2001, includeReReleaseDate: false, reReleaseYear: 2000))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(includeOriginalReleaseDate: false, originalReleaseYear: 2000, includeReReleaseDate: false, reReleaseYear: 2001))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + public void Validate_WhenGenresIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeGenres: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + + [Fact] + public void Validate_WhenTagsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeTags: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(includeOriginalLanguage: false)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(metadata: _audioMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenMusicBrainzRecordingIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzRecordingId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzRecordingIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzRecordingId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzTrackIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzTrackId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzTrackIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzTrackId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzWorkIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzWorkId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenMusicBrainzWorkIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(musicBrainzWorkId: Guid.NewGuid()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.MusicBrainzIdInvalidFormat); + } + + [Fact] + public void Validate_WhenTrackNumberIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeTrackNumber: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackNumberIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackNumber: 0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackNumberIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackNumber: -1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenTrackNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(trackNumber: 1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.TrackNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(discNumber: 0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(discNumber: -1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenDiscNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(discNumber: 1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.DiscNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenScriptExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(script: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenScriptIs50Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(script: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.ScriptMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenKeyIsInvalidEnum_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(key: (MusicKey)9999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenKeyIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(key: MusicKey.CMajor); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.UnknownMusicKey); + } + + [Fact] + public void Validate_WhenBpmIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(bpm: 0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenBpmIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(bpm: -1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenBpmIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(bpm: 120); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.BpmMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenWorkExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: new Faker().Random.String2(256)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenWorkIs255Characters_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(work: new Faker().Random.String2(255)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.WorkMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenMoodNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: string.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenMoodsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(moods: [_moodDtoFixture.Create(name: "dramatic")]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.MoodNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsrcValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create(value: string.Empty)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenIsrcValuesAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(isrcs: [_isrcDtoFixture.Create()]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Music.IsrcValueCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeContributors: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenContributorIdIsEmptyGuid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: (MediaContributorRole)9999)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Vocals)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); + } + + [Fact] + public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(includeRatings: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Fact] + public void Validate_WhenRatingValueIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 0, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: -1, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingValueIsGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Fact] + public void Validate_WhenRatingMaxValueIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: 0)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingMaxValueIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 1, maxValue: -1)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: -1)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenRatingsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Fact] + public void Validate_WhenRatingVoteCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(ratings: [_audioRatingDtoFixture.Create(value: 4, maxValue: 5, includeVoteCount: false)]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateTrackCommand command = _updateTrackCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandlerTests.cs new file mode 100644 index 00000000..c3eaae42 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandlerTests.cs @@ -0,0 +1,347 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IAlbumRepository _mockAlbumRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetTrackQueryHandler _sut; + private readonly Guid _userId; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly GetTrackQueryFixture _getTrackQueryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetTrackQueryHandlerTests() + { + _mockAlbumRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // Default stubs: the current user is authenticated and the library ownership policy allows access. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetTrackQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenTrackExists_ShouldReturnMappedTrackResponse() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", title: "Bohemian Rhapsody"); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + _mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(trackEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(trackId, result.Value.Id); + Assert.Equal(albumId, result.Value.AlbumId); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Equal("/music/queen/bohemian-rhapsody.flac", result.Value.Path); + Assert.Equal("Bohemian Rhapsody", result.Value.Metadata.Title); + Assert.Equal(trackEntity.TrackNumber, result.Value.TrackNumber); + Assert.NotNull(result.Value.Moods); + Assert.NotEmpty(result.Value.Moods!); + Assert.NotNull(result.Value.Isrcs); + Assert.NotEmpty(result.Value.Isrcs!); + Assert.NotNull(result.Value.Contributors); + Assert.NotEmpty(result.Value.Contributors!); + Assert.NotNull(result.Value.Ratings); + Assert.NotEmpty(result.Value.Ratings!); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == trackEntity.LibraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumNotFound_ShouldReturnAlbumNotFoundError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid albumId = Guid.Parse(query.AlbumId!); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: Guid.NewGuid(), libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The route artist id is enforced before the track is read, and the mismatch is reported as not found, without disclosing that the album exists under another artist. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumBelongsToAnotherLibrary_ShouldReturnAlbumNotFoundError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: Guid.NewGuid()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The route library id is enforced before the track is read, and the mismatch is reported as not found, without disclosing that the album exists in another library. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAlbumRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid albumId = Guid.Parse(query.AlbumId!); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackNotFound_ShouldReturnTrackNotFoundError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + _mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackBelongsToAnotherAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: Guid.NewGuid(), libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + _mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(trackEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The route album id is enforced, so a track of another album can never be read through this album's route. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackBelongsToAnotherLibrary_ShouldReturnTrackNotFoundError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: Guid.NewGuid()); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + _mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(trackEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + // The route library id is enforced, so a track of another library can never be read through this library's route. + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTrackRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + _mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Music.TrackIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + AlbumEntity albumEntity = _albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId); + TrackEntity trackEntity = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId); + _mockAlbumRepository.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(albumEntity)); + _mockTrackRepository.GetByIdAsync(trackId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(trackEntity)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == trackEntity.LibraryId), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.TrackIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackIdCannotBeEmpty, result.FirstError); + await _mockAlbumRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidatorTests.cs new file mode 100644 index 00000000..9d064313 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidatorTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackQueryValidatorTests +{ + private readonly GetTrackQueryFixture _getTrackQueryFixture = new(); + private readonly GetTrackQueryValidator _validator = new(); + + [Fact] + public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveValidationError(string? artistId) + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveValidationError(string? albumId) + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject + [InlineData("not-a-track-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveValidationError(string? trackId) + { + // Arrange + GetTrackQuery query = _getTrackQueryFixture.Create(trackId: trackId, includeTrackId: trackId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } +} 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 fc0ce989..153e4fe7 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 @@ -54,6 +54,7 @@ public class AddLibraryCommandHandlerTests public AddLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -84,7 +85,7 @@ public class AddLibraryCommandHandlerTests // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(persistedLibrary)); // Act @@ -123,7 +124,7 @@ public class AddLibraryCommandHandlerTests AddLibraryCommand command = _addLibraryCommandFixture.Create(); command = command with { CoverImage = null }; LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(persistedLibrary)); // Act @@ -261,7 +262,7 @@ public class AddLibraryCommandHandlerTests { // Arrange AddLibraryCommand command = _addLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs index cd47937e..a665f741 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class CancelLibrariesScanCommandHandlerTests public CancelLibrariesScanCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs index 6c9d3a7e..d8b40e6d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class CancelLibraryScanCommandHandlerTests public CancelLibraryScanCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockAuthorizationService = Substitute.For(); @@ -74,7 +75,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(runningScan)); // Act @@ -93,7 +94,7 @@ public class CancelLibraryScanCommandHandlerTests { // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -111,7 +112,7 @@ public class CancelLibraryScanCommandHandlerTests { // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library scan")); // Act @@ -129,7 +130,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(runningScan)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -157,7 +158,7 @@ public class CancelLibraryScanCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -167,7 +168,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId, status: LibraryScanJobStatus.Completed); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(completedScan)); // Act @@ -186,7 +187,7 @@ public class CancelLibraryScanCommandHandlerTests // Arrange CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); - _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken: Arg.Any()) .Returns(Result.From(runningScan)); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to update library scan")); @@ -212,7 +213,7 @@ public class CancelLibraryScanCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty, result.FirstError); - await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs index dae15900..7305b45a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs @@ -50,6 +50,7 @@ public class DeleteLibraryCommandHandlerTests public DeleteLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -78,7 +79,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -99,7 +100,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, Arg.Any()) .Returns(Error.Failure(description: "Failed to remove provider configurations")); @@ -118,7 +119,7 @@ public class DeleteLibraryCommandHandlerTests { // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -136,7 +137,7 @@ public class DeleteLibraryCommandHandlerTests { // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -154,7 +155,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -182,7 +183,7 @@ public class DeleteLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -192,7 +193,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, contentLocations: [""]); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -211,7 +212,7 @@ public class DeleteLibraryCommandHandlerTests // Arrange DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockLibraryRepository.DeleteByIdAsync(command.Id, Arg.Any()) .Returns(Error.Failure(description: "Failed to delete library")); @@ -237,7 +238,7 @@ public class DeleteLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs index 9fe9a29d..026ac2fd 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class ScanLibrariesCommandHandlerTests public ScanLibrariesCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs index 66b45d40..8398d34b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs @@ -52,6 +52,7 @@ public class ScanLibraryCommandHandlerTests public ScanLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); @@ -81,7 +82,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -100,7 +101,7 @@ public class ScanLibraryCommandHandlerTests { // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -118,7 +119,7 @@ public class ScanLibraryCommandHandlerTests { // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -136,7 +137,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -164,7 +165,7 @@ public class ScanLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -174,7 +175,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, isEnabled: false); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -193,7 +194,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, isLocked: true); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -212,7 +213,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, contentLocations: [""]); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -231,7 +232,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, Arg.Any()) .Returns(Error.Failure(description: "Failed to get past month scans")); @@ -251,7 +252,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: command.Id, userId: _userId, status: LibraryScanJobStatus.Running); _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, Arg.Any()) @@ -273,7 +274,7 @@ public class ScanLibraryCommandHandlerTests // Arrange ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockLibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to insert library scan")); @@ -299,7 +300,7 @@ public class ScanLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } 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 075425c5..942f528f 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 @@ -56,6 +56,7 @@ public class UpdateLibraryCommandHandlerTests public UpdateLibraryCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -89,7 +90,7 @@ public class UpdateLibraryCommandHandlerTests LibraryType commandLibraryType = Enum.Parse(command.LibraryType); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -112,7 +113,7 @@ public class UpdateLibraryCommandHandlerTests UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.LibraryType = Enum.Parse(command.LibraryType); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -131,7 +132,7 @@ public class UpdateLibraryCommandHandlerTests LibraryType commandLibraryType = Enum.Parse(command.LibraryType); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to reconcile provider configurations")); @@ -151,7 +152,7 @@ public class UpdateLibraryCommandHandlerTests UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = null }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -171,7 +172,7 @@ public class UpdateLibraryCommandHandlerTests command = command with { CoverImage = "C:/Users/user/cover.jpg" }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = null; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.None)); @@ -182,7 +183,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, result.FirstError); - await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -194,7 +195,7 @@ public class UpdateLibraryCommandHandlerTests command = command with { CoverImage = "C:/Users/user/cover.jpg" }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = null; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to determine image type")); @@ -204,7 +205,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); - await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -216,7 +217,7 @@ public class UpdateLibraryCommandHandlerTests command = command with { CoverImage = " " }; LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = null; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -225,7 +226,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); - await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -236,7 +237,7 @@ public class UpdateLibraryCommandHandlerTests UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); existingLibrary.CoverImage = command.CoverImage; - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); // Act @@ -246,7 +247,7 @@ public class UpdateLibraryCommandHandlerTests Assert.False(result.IsFailure); await _mockEnvironmentContext.FileTypeService.DidNotReceive() .GetImageTypeAsync(Arg.Any(), Arg.Any()); - await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, Arg.Any()); + await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, cancellationToken: Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -255,7 +256,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -273,7 +274,7 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -291,7 +292,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -321,7 +322,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -331,7 +332,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); command = command with { ContentLocations = [""] }; @@ -351,7 +352,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to update library")); @@ -370,7 +371,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Error.Failure(description: "Failed to retrieve updated library")); // Act @@ -386,7 +387,7 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From(existingLibrary), Result.Success(null)); // Act @@ -411,7 +412,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); 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/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryMediaItemDeletedDomainEventHandlerTests.cs index aec3802f..18d28223 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,7 +1,7 @@ #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.Books; +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.Events; @@ -68,15 +68,15 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests 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, Arg.Any()) + _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.DeleteAsync(book.Id, Arg.Any()) + _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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); @@ -85,7 +85,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId.Value, book.Id, "My Library", "Frank Herbert", book.Title); - await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -104,7 +104,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -117,15 +117,15 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests 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, Arg.Any()) + _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.DeleteAsync(book.Id, Arg.Any()) + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) .Returns(Result.From(Result.Deleted)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); @@ -134,7 +134,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert // a failing artwork deletion must not prevent the book from being removed, so the deletion is only logged - await _mockBookRepository.Received(1).DeleteAsync(book.Id, Arg.Any()); + await _mockBookRepository.Received(1).DeleteByIdAsync(book.Id, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -155,7 +155,7 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockBookRepository.DidNotReceive().DeleteAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -167,14 +167,14 @@ public class LibraryMediaItemDeletedDomainEventHandlerTests 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, Arg.Any()) + _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.DeleteAsync(book.Id, Arg.Any()) + _mockBookRepository.DeleteByIdAsync(book.Id, Arg.Any()) .Returns(error); LibraryMediaItemDeletedDomainEvent domainEvent = _libraryMediaItemDeletedDomainEventFixture.Create(libraryId: libraryId, path: book.Path); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs index b156d8c5..2a8d4282 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -55,6 +55,7 @@ public class LibrarySavedDomainEventHandlerTests public LibrarySavedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockEnvironmentContext = Substitute.For(); @@ -106,7 +107,7 @@ public class LibrarySavedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.NotNull(domainEvent.Library.CoverImage); + Assert.True(domainEvent.Library.CoverImage.HasValue); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -177,7 +178,7 @@ public class LibrarySavedDomainEventHandlerTests await _sut.HandleAsync(domainEvent, CancellationToken.None); // Assert - Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage); + Assert.Equal("/Media/Libraries/guid/cover.png", domainEvent.Library.CoverImage.Value); _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), Arg.Any()); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs index 0930c15e..2778b190 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs @@ -46,6 +46,7 @@ public class LibraryScanCancelledDomainEventHandlerTests public LibraryScanCancelledDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockLibraryScanStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); @@ -70,7 +71,7 @@ public class LibraryScanCancelledDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -89,7 +90,7 @@ public class LibraryScanCancelledDomainEventHandlerTests // Arrange LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -106,7 +107,7 @@ public class LibraryScanCancelledDomainEventHandlerTests { // Arrange LibraryScanCancelledDomainEvent domainEvent = _libraryScanCancelledDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -126,7 +127,7 @@ public class LibraryScanCancelledDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to cancel scan"); _mockMediaLibraryScanningService.CancelScan(Arg.Any()).Returns(error); @@ -149,7 +150,7 @@ public class LibraryScanCancelledDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to clear staging results"); _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs index 1d6d4e17..d3bc6ab6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs @@ -47,6 +47,7 @@ public class LibraryScanFailedDomainEventHandlerTests public LibraryScanFailedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockLibraryScanStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); @@ -73,7 +74,7 @@ public class LibraryScanFailedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -98,7 +99,7 @@ public class LibraryScanFailedDomainEventHandlerTests id: compositeId.ScanId.Value, userId: compositeId.UserId.Value, status: LibraryScanJobStatus.Failed); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -119,7 +120,7 @@ public class LibraryScanFailedDomainEventHandlerTests // Arrange LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -136,7 +137,7 @@ public class LibraryScanFailedDomainEventHandlerTests { // Arrange LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -157,7 +158,7 @@ public class LibraryScanFailedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to update library scan"); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -181,7 +182,7 @@ public class LibraryScanFailedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to clear staging results"); _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs index 8b7c7292..317bac60 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs @@ -46,6 +46,7 @@ public class LibraryScanFinishedDomainEventHandlerTests public LibraryScanFinishedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockMediaLibrariesScanProgressTracker = Substitute.For(); @@ -68,7 +69,7 @@ public class LibraryScanFinishedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); _mockMediaLibrariesScanProgressTracker.UpdateScanProgress(Arg.Any(), compositeId).Returns(Result.Updated); @@ -89,7 +90,7 @@ public class LibraryScanFinishedDomainEventHandlerTests // Arrange LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -106,7 +107,7 @@ public class LibraryScanFinishedDomainEventHandlerTests { // Arrange LibraryScanFinishedDomainEvent domainEvent = _libraryScanFinishedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -128,7 +129,7 @@ public class LibraryScanFinishedDomainEventHandlerTests id: compositeId.ScanId.Value, userId: compositeId.UserId.Value, status: LibraryScanJobStatus.Pending); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -150,7 +151,7 @@ public class LibraryScanFinishedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: compositeId.ScanId.Value, userId: compositeId.UserId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to update library scan"); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs index 7a868cf1..409bfbf3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs @@ -43,6 +43,7 @@ public class LibraryScanQueuedDomainEventHandlerTests public LibraryScanQueuedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockMediaLibraryScanningService = Substitute.For(); @@ -63,7 +64,7 @@ public class LibraryScanQueuedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); // Act @@ -82,7 +83,7 @@ public class LibraryScanQueuedDomainEventHandlerTests // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); Error error = Error.Failure(description: "Failed to get library scan"); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(error); // Act @@ -99,7 +100,7 @@ public class LibraryScanQueuedDomainEventHandlerTests { // Arrange LibraryScanQueuedDomainEvent domainEvent = _libraryScanQueuedDomainEventFixture.Create(); - _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -119,7 +120,7 @@ public class LibraryScanQueuedDomainEventHandlerTests LibraryScanEntity scan = _libraryScanEntityFixture.Create( id: domainEvent.ScanId.Value, libraryId: domainEvent.LibraryId.Value); - _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + _mockLibraryScanRepository.GetByIdAsync(scan.Id, cancellationToken: Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to start scan"); _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs index 7fcc2a37..5c5e8d9c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs @@ -34,6 +34,7 @@ public class LibraryScanStartedDomainEventHandlerTests public LibraryScanStartedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs index a1ed34ef..4106c121 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs @@ -41,6 +41,7 @@ public class GetEnabledLibrariesQueryHandlerTests public GetEnabledLibrariesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); 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 e69ccda4..fc3f6920 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 @@ -2,6 +2,8 @@ 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.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -41,6 +43,7 @@ public class GetLibrariesQueryHandlerTests public GetLibrariesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -63,7 +66,7 @@ public class GetLibrariesQueryHandlerTests _libraryEntityFixture.Create(userId: _userId), _libraryEntityFixture.Create(userId: Guid.NewGuid()) ]; - _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = libraries, CurrentPage = 1, PerPage = libraries.Count, Count = libraries.Count, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); @@ -85,7 +88,7 @@ public class GetLibrariesQueryHandlerTests _libraryEntityFixture.Create(userId: _userId), _libraryEntityFixture.Create(userId: otherUserId) ]; - _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = libraries, CurrentPage = 1, PerPage = libraries.Count, Count = libraries.Count, NumberOfPages = 1 })); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act @@ -109,14 +112,14 @@ public class GetLibrariesQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] public async Task HandleAsync_WhenGetAllFails_ShouldReturnError() { // Arrange - _mockLibraryRepository.GetAllAsync(Arg.Any()) + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get libraries")); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs index 45bf6b28..e0036c14 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs @@ -47,6 +47,7 @@ public class GetLibraryQueryHandlerTests { _mockLibraryRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -57,7 +58,7 @@ public class GetLibraryQueryHandlerTests _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.From((LibraryEntity?)_libraryEntityFixture.Create(userId: _userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []))); _mockValidator.Validate(Arg.Any()).Returns([]); @@ -110,7 +111,7 @@ public class GetLibraryQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -118,7 +119,7 @@ public class GetLibraryQueryHandlerTests { // Arrange GetLibraryQuery query = _getLibraryQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -134,7 +135,7 @@ public class GetLibraryQueryHandlerTests { // Arrange GetLibraryQuery query = _getLibraryQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryNotFound); // Act @@ -159,6 +160,6 @@ public class GetLibraryQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs index f9a061fc..986e8dde 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs @@ -53,6 +53,7 @@ public class GetLibraryScanProgressQueryHandlerTests public GetLibraryScanProgressQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -82,7 +83,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -100,7 +101,7 @@ public class GetLibraryScanProgressQueryHandlerTests { // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -117,7 +118,7 @@ public class GetLibraryScanProgressQueryHandlerTests { // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get library")); // Act @@ -134,7 +135,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -161,7 +162,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -170,7 +171,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Arrange GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); - _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) .Returns(Error.Failure(description: "Failed to get scan progress")); @@ -195,7 +196,7 @@ public class GetLibraryScanProgressQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); _mockMediaLibrariesScanProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs index fea2650e..dd128719 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs @@ -50,6 +50,7 @@ public class GetRunningLibraryScansQueryHandlerTests public GetRunningLibraryScansQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryScanRepository = Substitute.For(); _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); _mockAuthorizationService = Substitute.For(); 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 6575ebc0..f2c3dfa9 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 @@ -2,9 +2,11 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; 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.Repositories.Books; +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.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -12,6 +14,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.Setup; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook; using Lumina.Contracts.Fixtures.Core.DTO.Common; @@ -21,11 +24,15 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -42,9 +49,12 @@ public class AddBookCommandHandlerTests private readonly IFixture _fixture; private readonly IUnitOfWork _mockUnitOfWork; private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; private readonly IMediaContributorRepository _mockMediaContributorRepository; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly IPathService _mockPathService; private readonly Guid _userId; private readonly AddBookCommandHandler _sut; private readonly AddBookCommandFixture _commandBookFixture = new(); @@ -53,10 +63,9 @@ public class AddBookCommandHandlerTests private readonly GenreDtoFixture _genreDtoFixture = new(); private readonly TagDtoFixture _tagDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); - private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); - private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -69,24 +78,66 @@ public class AddBookCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockBookRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); _mockMediaContributorRepository = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); + _mockPathService = Substitute.For(); _userId = Guid.NewGuid(); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(_mediaContributorEntityFixture.Create())); + // Default stub: saving changes succeeds. + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Default stubs: the current user is authenticated and the library ownership policy allows access. _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + // Default stub: the book path is inside the content locations of the library. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(true); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .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 + })]); + }); IValidator mockValidator = Substitute.For>(); mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, mockValidator); + _mockValidator = mockValidator; + _sut = new AddBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator, _mockPathService); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsErrors_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([Errors.WrittenContent.IsbnListCannotBeNull]); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.IsbnListCannotBeNull, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -95,8 +146,15 @@ public class AddBookCommandHandlerTests // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(); + BookEntity? insertedEntity = null; _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Created); + .Returns(callInfo => + { + insertedEntity = callInfo.Arg(); + return Result.Created; + }); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(insertedEntity)); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -127,6 +185,26 @@ public class AddBookCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenSaveChangesDetectsAConcurrentDuplicatePath_ShouldReturnThePersistenceError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCalledWithInvalidISBN_ShouldReturnFailureResult() { @@ -148,7 +226,7 @@ public class AddBookCommandHandlerTests public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)]); + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeSource: false, includeVoteCount: false)]); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -216,53 +294,17 @@ public class AddBookCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenLanguageInfoCreationFails_ShouldReturnFailureResult() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English"))); - - // Act - Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); - await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - - [Fact] - public async Task HandleAsync_WhenOriginalLanguageInfoCreationFails_ShouldReturnFailureResult() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: "", languageName: "English"))); - - // Act - Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Contains(result.Errors, e => e.Description == Errors.Metadata.LanguageCodeCannotBeEmpty.Description); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); - await _mockMediaContributorRepository.DidNotReceive().FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - [Fact] public async Task HandleAsync_WhenContributorsAreLinked_ShouldAttachBookContributorRowsAndReturnThemInTheResponse() { // Arrange + Guid firstContributorId = Guid.NewGuid(); + Guid secondContributorId = Guid.NewGuid(); AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [ - _mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator) ]); - MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(); - MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(callInfo => Result.From(callInfo.ArgAt(0) == "Author One" ? firstContributor : secondContributor)); BookEntity? insertedEntity = null; _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => @@ -270,37 +312,33 @@ public class AddBookCommandHandlerTests insertedEntity = callInfo.Arg(); return Result.Created; }); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(insertedEntity)); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal(bookCommand.Contributors, result.Value.Contributors); Assert.NotNull(insertedEntity); - Assert.Equal(2, insertedEntity!.BookContributors.Count); - Assert.Equal(firstContributor.Id, insertedEntity.BookContributors[0].MediaContributorId); - Assert.Equal("author", insertedEntity.BookContributors[0].RoleName); - Assert.Equal(MediaContributorRoleCategory.Author, insertedEntity.BookContributors[0].RoleCategory); - Assert.Equal(secondContributor.Id, insertedEntity.BookContributors[1].MediaContributorId); - Assert.Equal("illustrator", insertedEntity.BookContributors[1].RoleName); - Assert.Equal(MediaContributorRoleCategory.Illustrator, insertedEntity.BookContributors[1].RoleCategory); + Assert.Equal(2, insertedEntity!.Contributors.Count); + Assert.Contains(insertedEntity.Contributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author); + Assert.Contains(insertedEntity.Contributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator); await _mockBookRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole() + public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnlyOnce() { // Arrange + Guid contributorId = Guid.NewGuid(); AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [ - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator) ]); - MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(contributor)); BookEntity? insertedEntity = null; _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => @@ -308,73 +346,22 @@ public class AddBookCommandHandlerTests insertedEntity = callInfo.Arg(); return Result.Created; }); + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(insertedEntity)); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert Assert.False(result.IsFailure); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "John Doe", "John Smith Doe", Arg.Any()); Assert.NotNull(insertedEntity); - Assert.Equal(2, insertedEntity!.BookContributors.Count); - Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId)); - Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author"); - Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator"); + Assert.Equal(2, insertedEntity!.Contributors.Count); + Assert.All(insertedEntity.Contributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId)); + Assert.Contains(insertedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author); + Assert.Contains(insertedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenContributorHasNullDisplayName_ShouldSkipIt() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: - [ - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(includeName: false, roleName: "unknown", roleCategory: MediaContributorRoleCategory.Other) - ]); - MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(contributor)); - BookEntity? insertedEntity = null; - _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => - { - insertedEntity = callInfo.Arg(); - return Result.Created; - }); - - // Act - Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); - - // Assert - Assert.False(result.IsFailure); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "John Doe", "John Smith Doe", Arg.Any()); - Assert.NotNull(insertedEntity); - Assert.Single(insertedEntity!.BookContributors); - Assert.Equal(contributor.Id, insertedEntity.BookContributors[0].MediaContributorId); - } - - [Fact] - public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutInserting() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(); - Error findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor."); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(findOrCreateError); - - // Act - Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(findOrCreateError, result.FirstError); - await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - [Fact] public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() { @@ -407,33 +394,62 @@ public class AddBookCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == bookCommand.LibraryId), Arg.Any()); + _userId, Arg.Is(context => context.LibraryId == Guid.Parse(bookCommand.LibraryId!)), Arg.Any()); await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenCalledWithValidCommand_ShouldStampTheCurrentUserAsTheAuditActor() + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnFailureResultWithoutPersisting() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create()]); - BookEntity? insertedEntity = null; - _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) - .Returns(callInfo => - { - insertedEntity = callInfo.Arg(); - return Result.Created; - }); + AddBookCommand bookCommand = _commandBookFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(null)); // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); // Assert - Assert.False(result.IsFailure); - Assert.NotNull(insertedEntity); - Assert.Equal(_userId, insertedEntity!.CreatedBy); - Assert.NotEmpty(insertedEntity.BookContributors); - Assert.All(insertedEntity.BookContributors, contributor => Assert.Equal(_userId, contributor.CreatedBy)); - await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookPathIsNotWithinTheLibraryContentLocations_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookPathMustBeWithinLibraryContentLocations, result.FirstError); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create()]); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } } 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 9e1631f1..49af0de5 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; @@ -35,7 +35,20 @@ public class AddBookCommandValidatorTests private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + + [Fact] + public void Validate_WhenPathIsLongerThan2048Characters_ShouldHaveValidationError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(path: "/" + new Faker().Random.String2(2048) + ".epub"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookPathMustBeMaximum2048CharactersLong); + } [Fact] public void Validate_WhenTitleIsNull_ShouldHaveValidationError() @@ -197,7 +210,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, 0, null, null, null, null))); + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); // Act List result = _validator.TestValidate(bookCommand); @@ -210,7 +223,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, 10000, null, null, null, null))); + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); // Act List result = _validator.TestValidate(bookCommand); @@ -236,7 +249,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, null, null, 0, null, null))); + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); // Act List result = _validator.TestValidate(bookCommand); @@ -249,7 +262,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: new ReleaseInfoDto(null, null, null, 10000, null, null))); + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); // Act List result = _validator.TestValidate(bookCommand); @@ -479,6 +492,19 @@ public class AddBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); } + [Fact] + public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + [Fact] public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() { @@ -557,6 +583,19 @@ public class AddBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } + [Fact] + public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + [Fact] public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() { @@ -717,7 +756,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenFormatIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -756,7 +795,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenEditionIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -795,7 +834,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenVolumeNumberIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -915,7 +954,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenAsinIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -941,7 +980,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenGoodreadsIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1006,7 +1045,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenLccnIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1071,7 +1110,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyOclcNumber_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1162,7 +1201,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenOpenLibraryIdIsNull_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1224,10 +1263,10 @@ public class AddBookCommandValidatorTests } [Fact] - public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldAddBook() + public void Validate_WhenCalledWithEmptyLibraryThingId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1250,7 +1289,7 @@ public class AddBookCommandValidatorTests } [Fact] - public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldReturnBadRequest() + public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError() { // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51)); @@ -1266,7 +1305,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyGoogleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1318,7 +1357,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithEmptyBarnesAndNobleId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1367,10 +1406,10 @@ public class AddBookCommandValidatorTests } [Fact] - public void AddBook_WhenCalledWithEmptyAppleBooksId_ShouldAddBook() + public void Validate_WhenCalledWithEmptyAppleBooksId_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1380,7 +1419,7 @@ public class AddBookCommandValidatorTests } [Fact] - public void AddBook_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() + public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() { // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456"); @@ -1393,7 +1432,7 @@ public class AddBookCommandValidatorTests } [Fact] - public void AddBook_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() + public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() { // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id"); @@ -1409,7 +1448,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1497,10 +1536,10 @@ public class AddBookCommandValidatorTests } [Fact] - public void Validate_WhenCalledWithNullContributors_ShouldHaveValidationError() + public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + AddBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null }; // Act List result = _validator.TestValidate(bookCommand); @@ -1510,114 +1549,49 @@ public class AddBookCommandValidatorTests } [Fact] - public void Validate_WhenCalledWithNullContributorName_ShouldHaveValidationError() + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(null, new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]); + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] - public void Validate_WhenCalledWithInvalidLengthContributorDisplayName_ShouldHaveValidationError() + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: new Faker().Random.String2(101))]); + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong); + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); } [Fact] - public void Validate_WhenCalledWithEmptyContributorDisplayName_ShouldHaveValidationError() + public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]); + AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCalledWithInvalidLengthContributorLegalName_ShouldHaveValidationError() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), new Faker().Random.String2(101)), new MediaContributorRoleDto("author", MediaContributorRoleCategory.Author))]); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong); - } - - [Fact] - public void Validate_WhenCalledWithNullContributorRole_ShouldHaveValidationError() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), null)]); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorRoleCannotBeNull); - } - - [Fact] - public void Validate_WhenCalledWithEmptyContributorRoleName_ShouldHaveValidationError() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(null, MediaContributorRoleCategory.Author))]); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameCannotBeEmpty); - } - - [Fact] - public void Validate_WhenCalledWithInvalidLengthContributorRoleName_ShouldHaveValidationError() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto(new Faker().Random.String2(51), MediaContributorRoleCategory.Author))]); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong); - } - - [Fact] - public void Validate_WhenCalledWithEmptyContributorRoleCategory_ShouldHaveValidationError() - { - // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(contributors: [new MediaContributorDto(new MediaContributorNameDto(new Faker().Random.String2(50), null), new MediaContributorRoleDto("author", null))]); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.RoleCategoryCannotBeEmpty); + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); } [Fact] public void Validate_WhenCalledWithNullRatings_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -1695,7 +1669,7 @@ public class AddBookCommandValidatorTests public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeOptionalProperties: false)]); + AddBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false)]); // Act List result = _validator.TestValidate(bookCommand); @@ -1708,12 +1682,12 @@ public class AddBookCommandValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty); + AddBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.WrittenContent.BookLibraryCannotBeNull); + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); } } 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 8bc4854e..c7eb1b3e 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 @@ -1,8 +1,10 @@ #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.Repositories.Books; +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.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -10,9 +12,13 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; 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.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBook; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +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.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -39,17 +45,23 @@ public class UpdateBookCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IBookRepository _mockBookRepository; + private readonly ILibraryRepository _mockLibraryRepository; private readonly IMediaContributorRepository _mockMediaContributorRepository; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly UpdateBookCommandHandler _sut; private readonly Guid _userId; - private static readonly Error s_findOrCreateError = Error.Validation("MediaContributor.FindOrCreate", "Could not find or create the media contributor."); private readonly UpdateBookCommandFixture _commandBookFixture = new(); private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); - private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -57,9 +69,12 @@ public class UpdateBookCommandHandlerTests public UpdateBookCommandHandlerTests() { _mockBookRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); _mockMediaContributorRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -72,10 +87,25 @@ public class UpdateBookCommandHandlerTests _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); _mockValidator.Validate(Arg.Any()).Returns([]); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(_mediaContributorEntityFixture.Create())); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); + // Default stub: the library of the book exists. + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_ => Result.From(_libraryEntityFixture.Create())); + // Default stub: every referenced media contributor already exists. + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .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 + })]); + }); _sut = new UpdateBookCommandHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator); } @@ -85,18 +115,25 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); + 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()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedBook)); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => + { + updatedBook = callInfo.Arg(); + return Result.Updated; + }); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal(command.Id, result.Value.Id); + Assert.Equal(Guid.Parse(command.BookId!), result.Value.Id); Assert.Equal(command.Metadata!.Title, result.Value.Metadata!.Title); - Assert.Equal(command.Contributors, result.Value.Contributors); + Assert.Equal(command.Contributors!.Count, result.Value.Contributors!.Count); await _mockBookRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -114,7 +151,7 @@ public class UpdateBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -131,7 +168,7 @@ public class UpdateBookCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -139,7 +176,7 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -157,7 +194,7 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryIdCannotBeEmpty); // Act @@ -174,8 +211,8 @@ public class UpdateBookCommandHandlerTests { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + 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)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -192,34 +229,13 @@ public class UpdateBookCommandHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } - [Fact] - public async Task HandleAsync_WhenContributorFindOrCreateFails_ShouldReturnFailureResultWithoutSaving() - { - // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(s_findOrCreateError); - - // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(s_findOrCreateError, result.FirstError); - await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); - await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); - } - [Fact] public async Task HandleAsync_WhenRepositoryUpdateFails_ShouldReturnFailureResultWithoutSaving() { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + 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)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Errors.WrittenContent.BookNotFound); @@ -234,22 +250,21 @@ public class UpdateBookCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenContributorsShareTheSameDisplayName_ShouldResolveContributorOnceAndLinkEveryRole() + public async Task HandleAsync_WhenContributorsHaveTheSameIdAndRole_ShouldLinkThemOnce() { // Arrange + Guid contributorId = Guid.NewGuid(); UpdateBookCommand command = _commandBookFixture.Create( contributors: [ - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: contributorId, role: MediaContributorRole.Illustrator) ]); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); - MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(contributor)); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); BookEntity? updatedEntity = null; + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedEntity)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => { @@ -262,34 +277,30 @@ public class UpdateBookCommandHandlerTests // Assert Assert.False(result.IsFailure); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "John Doe", "John Smith Doe", Arg.Any()); Assert.NotNull(updatedEntity); - Assert.Equal(2, updatedEntity!.BookContributors.Count); - Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributor.Id, linkedContributor.MediaContributorId)); - Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "author"); - Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.RoleName == "illustrator"); + Assert.Equal(2, updatedEntity!.Contributors.Count); + Assert.All(updatedEntity.Contributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId)); + Assert.Contains(updatedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author); + Assert.Contains(updatedEntity.Contributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Illustrator); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenContributorsHaveDistinctDisplayNames_ShouldResolveEachContributorOnce() + public async Task HandleAsync_WhenContributorsHaveDistinctIds_ShouldLinkEachContributor() { // Arrange + Guid firstContributorId = Guid.NewGuid(); + Guid secondContributorId = Guid.NewGuid(); UpdateBookCommand command = _commandBookFixture.Create( contributors: [ - _mediaContributorDtoFixture.Create(displayName: "Author One", legalName: "Author One Legal", roleName: "author", roleCategory: MediaContributorRoleCategory.Author), - _mediaContributorDtoFixture.Create(displayName: "Author Two", legalName: "Author Two Legal", roleName: "illustrator", roleCategory: MediaContributorRoleCategory.Illustrator) + _mediaContributorReferenceDtoFixture.Create(contributorId: firstContributorId, role: MediaContributorRole.Author), + _mediaContributorReferenceDtoFixture.Create(contributorId: secondContributorId, role: MediaContributorRole.Illustrator) ]); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) - .Returns(Result.From(existingBook)); - MediaContributorEntity firstContributor = _mediaContributorEntityFixture.Create(); - MediaContributorEntity secondContributor = _mediaContributorEntityFixture.Create(); - _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(callInfo => Result.From(callInfo.ArgAt(0) == "Author One" ? firstContributor : secondContributor)); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); BookEntity? updatedEntity = null; + _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(callInfo.ArgAt(2) ? existingBook : updatedEntity)); _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(callInfo => { @@ -302,51 +313,172 @@ public class UpdateBookCommandHandlerTests // Assert Assert.False(result.IsFailure); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "Author One", "Author One Legal", Arg.Any()); - await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync( - "Author Two", "Author Two Legal", Arg.Any()); Assert.NotNull(updatedEntity); - Assert.Equal(2, updatedEntity!.BookContributors.Count); - Assert.Equal(firstContributor.Id, updatedEntity.BookContributors[0].MediaContributorId); - Assert.Equal(secondContributor.Id, updatedEntity.BookContributors[1].MediaContributorId); + Assert.Equal(2, updatedEntity!.Contributors.Count); + Assert.Equal(firstContributorId, updatedEntity.Contributors[0].MediaContributorId); + Assert.Equal(secondContributorId, updatedEntity.Contributors[1].MediaContributorId); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } [Fact] - public async Task HandleAsync_WhenStoredBookHasEnrichmentAndCover_ShouldPreserveThemInTheResponse() + public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.WrittenContent.InvalidIsbn13Format.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalledWithInvalidRating_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.RatingValueMustBePositive.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGenreCreationFails_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.GenreNameCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTagCreationFails_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.TagNameCannotBeEmpty.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenReleaseInfoCreationFails_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2025, 1, 1), + originalReleaseYear: 2025, + reReleaseDate: new DateOnly(2024, 1, 1), + reReleaseYear: 2024))); + 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)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Contains(result.Errors, error => error.Description == Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAReferencedContributorDoesNotExist_ShouldReturnFailureResultWithoutPersisting() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.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)); + _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.MediaContributor.MediaContributorNotFound, result.FirstError); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() { // Arrange UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.Id); - existingBook.MetadataStatus = MetadataStatus.Enriched; - existingBook.LastMetadataUpdateUtc = new DateTime(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc); - existingBook.MetadataProvider = "TestProvider"; - existingBook.BookArtwork.Add(new BookArtworkEntity - { - Id = Guid.NewGuid(), - BookId = existingBook.Id, - ArtworkType = ArtworkType.Cover, - Ordinal = 0, - FileName = "/media/covers/cover.jpg", - Status = ArtworkStatus.Enriched, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedBy = null - }); - _mockBookRepository.GetByIdAsync(command.Id, Arg.Any()) + // 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()) .Returns(Result.From(existingBook)); - _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) - .Returns(Result.Updated); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsFailure); - Assert.Equal(MetadataStatus.Enriched, result.Value.MetadataStatus); - Assert.Equal(existingBook.LastMetadataUpdateUtc, result.Value.LastMetadataUpdateUtc); - Assert.Equal(existingBook.MetadataProvider, result.Value.MetadataProvider); - Assert.Equal("/media/covers/cover.jpg", result.Value.CoverPath); + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundErrorWithoutUpdating() + { + // Arrange + UpdateBookCommand command = _commandBookFixture.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)); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } } 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 3decf083..7f8efc2a 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,8 +1,10 @@ -#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; using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; @@ -10,6 +12,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -27,49 +30,12 @@ public class UpdateBookCommandValidatorTests private readonly UpdateBookCommandValidator _validator = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); private readonly IsbnDtoFixture _isbnDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - - [Fact] - public void Validate_WhenCommandIsValid_ShouldNotHaveValidationErrors() - { - // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - Assert.Empty(result); - } - - [Fact] - public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(id: Guid.Empty); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenMetadataIsNull_ShouldHaveValidationError() - { - // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeMetadata: false); - - // Act - List result = _validator.TestValidate(bookCommand); - - // Assert - result.ShouldHaveValidationError(Errors.Metadata.MetadataCannotBeNull); - } + private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new(); [Fact] public void Validate_WhenTitleIsNull_ShouldHaveValidationError() @@ -97,6 +63,110 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.TitleMustBeMaximum255CharactersLong); } + [Fact] + public void Validate_WhenTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(title: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalTitleExceeds255Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(300))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalTitle: new Faker().Random.String2(200))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalTitleIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalTitle: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionExceeds2000Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(2001))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: new Faker().Random.String2(1500))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeDescription: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsEmpty_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(description: string.Empty)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong); + } + [Fact] public void Validate_WhenReleaseInfoIsNull_ShouldHaveValidationError() { @@ -110,6 +180,123 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.ReleaseInfoCannotBeNull); } + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenOriginalReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999); + } + + [Fact] + 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))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsLessThan1_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 0))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReReleaseYearIsGreaterThan9999_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(reReleaseYear: 10000))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999); + } + + [Fact] + public void Validate_WhenReleaseVersionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(50)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReleaseVersionExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(releaseVersion: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenReReleaseYearIsAfterOriginalReleaseYear_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseYear: 2000, reReleaseYear: 2001, includeReReleaseDate: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); + } + [Fact] public void Validate_WhenReReleaseYearIsBeforeOriginalReleaseYear_ShouldHaveValidationError() { @@ -123,6 +310,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear); } + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + + [Fact] + 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)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate); + } + [Fact] public void Validate_WhenGenresIsNull_ShouldHaveValidationError() { @@ -136,6 +349,45 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.GenresListCannotBeNull); } + [Fact] + public void Validate_WhenGenreNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenGenreNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenGenresAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(genres: [_genreDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.GenresListCannotBeNull); + } + [Fact] public void Validate_WhenTagsIsNull_ShouldHaveValidationError() { @@ -149,6 +401,58 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.TagsListCannotBeNull); } + [Fact] + public void Validate_WhenTagNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: string.Empty)])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTagNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(51))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenTagsAreValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(tags: [_tagDtoFixture.Create(name: new Faker().Random.String2(50))])); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TagsListCannotBeNull); + } + + [Fact] + public void Validate_WhenLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeLanguage: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + [Fact] public void Validate_WhenLanguageCodeIsEmpty_ShouldHaveValidationError() { @@ -162,6 +466,305 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); } + [Fact] + public void Validate_WhenLanguageCodeExceeds2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(language: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includeOriginalLanguage: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeIsShorterThan2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(1)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageCodeExceeds2Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageCode: new Faker().Random.String2(3)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageCodeMustBe2CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: string.Empty))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOriginalLanguageNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(languageName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(includeNativeName: false))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenOriginalLanguageNativeNameExceeds50Characters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(originalLanguage: _languageInfoDtoFixture.Create(nativeName: new Faker().Random.String2(51)))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithEmptyPublisher_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePublisher: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithValidPublisher_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(100))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthPublisher_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(publisher: new Faker().Random.String2(101))); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong); + } + + [Fact] + public void Validate_WhenPageCountIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(includePageCount: false)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenPageCountIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 0)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenPageCountIsNegative_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: -1)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenPageCountIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(metadata: _writtenContentMetadataDtoFixture.Create(pageCount: 100)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.PageCountMustBeGreaterThanZero); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.UnknownBookFormat); + } + + [Fact] + public void Validate_WhenFormatIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(format: BookFormat.Hardcover); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.UnknownBookFormat); + } + [Fact] public void Validate_WhenFormatIsInvalid_ShouldHaveValidationError() { @@ -175,6 +778,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.UnknownBookFormat); } + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenEditionIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(edition: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); + } + [Fact] public void Validate_WhenEditionExceeds50Characters_ShouldHaveValidationError() { @@ -188,6 +817,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong); } + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenVolumeNumberIsZero_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 0); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + [Fact] public void Validate_WhenVolumeNumberIsNegative_ShouldHaveValidationError() { @@ -201,6 +856,100 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); } + [Fact] + public void Validate_WhenVolumeNumberIsPositive_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(volumeNumber: 1); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero); + } + + [Fact] + public void Validate_WhenSeriesIsNull_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.TitleCannotBeEmpty); + } + + //[Fact] + //public void Validate_WhenSeriesTitleIsEmpty_ShouldHaveValidationError() + //{ + // // Arrange + // var bookCommand = _commandBookFixture.Create(); + // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = string.Empty } }; + + // // Act + // var result = _validator.TestValidate(bookCommand); + + // // Assert + // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleCannotBeEmpty.Description); + //} + + //[Fact] + //public void Validate_WhenSeriesTitleExceeds255Characters_ShouldHaveValidationError() + //{ + // // Arrange + // var bookCommand = _commandBookFixture.Create(); + // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(256) } }; + + // // Act + // var result = _validator.TestValidate(bookCommand); + + // // Assert + // result.ShouldHaveValidationErrorFor(x => x.Series.Title).WithErrorMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description); + //} + + //[Fact] + //public void Validate_WhenSeriesTitleIsValid_ShouldNotHaveValidationError() + //{ + // // Arrange + // var bookCommand = _commandBookFixture.Create(); + // bookCommand = bookCommand with { Series = bookCommand.Series! with { Title = new Faker().Random.String2(200) } }; + + // // Act + // var result = _validator.TestValidate(bookCommand); + + // // Assert + // result.ShouldNotHaveValidationErrorFor(x => x.Series.Title); + //} + + [Fact] + public void Validate_WhenAsinIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(asin: new Faker().Random.String2(10)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); + } + [Fact] public void Validate_WhenAsinIsNotTenCharacters_ShouldHaveValidationError() { @@ -214,6 +963,32 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.AsinMustBe10CharactersLong); } + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + public void Validate_WhenGoodreadsIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123456789"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + [Fact] public void Validate_WhenGoodreadsIdIsNonNumeric_ShouldHaveValidationError() { @@ -227,6 +1002,58 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); } + [Fact] + public void Validate_WhenGoodreadsIdContainsSpaces_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123 456"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + public void Validate_WhenGoodreadsIdContainsSpecialCharacters_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(goodreadsId: "123-456"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.GoodreadsIdMustBeNumeric); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + public void Validate_WhenLccnIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "n78890351"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + [Fact] public void Validate_WhenLccnHasInvalidFormat_ShouldHaveValidationError() { @@ -241,7 +1068,111 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenOclcNumberHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenLccnIsTooLong_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: new Faker().Random.String2(15)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + public void Validate_WhenLccnIsTooShort_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(lccn: "n12"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidLccnFormat); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat1_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocm12345678"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat2_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "ocn123456789"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat3_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "on1234567890"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat4_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "(OCoLC)1234567890"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidOclcNumberFormat5_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "12345678"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOclcFormat); + } + + [Fact] + public void Validate_WhenCalledWithInvalidOclcNumber_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(oclcNumber: "invalid_oclc_number"); @@ -254,7 +1185,33 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenOpenLibraryIdHasInvalidFormat_ShouldHaveValidationError() + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenOpenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456M"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenOpenLibraryIdIsInvalid_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "InvalidID"); @@ -267,10 +1224,88 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenGoogleBooksIdHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenOpenLibraryIdStartsWithOLButIsInvalidFormat_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: "invalid!"); + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123ABC"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + public void Validate_WhenOpenLibraryIdHasValidFormatButInvalidSuffix_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(openLibraryId: "OL123456X"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidOpenLibraryId); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithValidLibraryThingId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(50)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthLibraryThingId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryThingId: new Faker().Random.String2(51)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthGoogleBooksId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -280,10 +1315,49 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenBarnesAndNobleIdIsNotTenDigits_ShouldHaveValidationError() + public void Validate_WhenCalledWithInvalidFormatGoogleBooksId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: "abc123"); + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(11) + " "); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidGoogleBooksIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidGoogleBooksId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(googleBooksId: new Faker().Random.String2(12, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); + } + + [Fact] + public void Validate_WhenCalledWithInvalidLengthBarnesAndNobleId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.String2(11)); // Act List result = _validator.TestValidate(bookCommand); @@ -293,10 +1367,62 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenAppleBooksIdHasInvalidFormat_ShouldHaveValidationError() + public void Validate_WhenCalledWithNonNumericBarnesAndNobleId_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "395211"); + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.AlphaNumeric(10)); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidBarnesAndNobleId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(barnesAndNobleId: new Faker().Random.Number(1000000000, 999999999).ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong); + } + + [Fact] + 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); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidAppleBooksId_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "id123456"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidAppleBooksIdFormat); + } + + [Fact] + public void Validate_WhenCalledWithInvalidAppleBooksId_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(appleBooksId: "invalid_id"); // Act List result = _validator.TestValidate(bookCommand); @@ -306,10 +1432,10 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenIsbnsIsNull_ShouldHaveValidationError() + public void Validate_WhenCalledWithNullIsbns_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -319,7 +1445,7 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenIsbnValueIsEmpty_ShouldHaveValidationError() + public void Validate_WhenCalledWithEmptyIsbnValue_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: string.Empty)]); @@ -332,10 +1458,23 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenIsbn13ValueIsInvalid_ShouldHaveValidationError() + public void Validate_WhenCalledWithInvalidIsbn10Value_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)]); + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn10)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn10Format); + } + + [Fact] + public void Validate_WhenCalledWithInvalidIsbn13Value_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: new Faker().Random.String2(5), format: IsbnFormat.Isbn13)]); // Act List result = _validator.TestValidate(bookCommand); @@ -344,11 +1483,50 @@ public class UpdateBookCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); } + [Fact] + public void Validate_WhenCalledWithInvalidIsbnFormat_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(format: (IsbnFormat)99)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.UnknownIsbnFormat); + } + + [Fact] + public void Validate_WhenCalledWithValidIsbn10_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidIsbn10Format); + } + + [Fact] + public void Validate_WhenCalledWithValidIsbn13_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(isbns: [_isbnDtoFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.InvalidIsbn13Format); + } + [Fact] public void Validate_WhenContributorsIsNull_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + UpdateBookCommand bookCommand = _commandBookFixture.Create() with { Contributors = null }; // Act List result = _validator.TestValidate(bookCommand); @@ -358,23 +1536,49 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenContributorDisplayNameIsEmpty_ShouldHaveValidationError() + public void Validate_WhenContributorsAreValid_ShouldNotHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorDtoFixture.Create(displayName: string.Empty)]); + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(role: MediaContributorRole.Author)]); // Act List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] - public void Validate_WhenRatingsIsNull_ShouldHaveValidationError() + public void Validate_WhenContributorIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCommand bookCommand = _commandBookFixture.Create(includeOptionalProperties: false); + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.Empty, role: MediaContributorRole.Author)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.MediaContributorIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenContributorRoleIsInvalid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(contributors: [_mediaContributorReferenceDtoFixture.Create(contributorId: Guid.NewGuid(), role: (MediaContributorRole)999)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.MediaContributor.UnknownMediaContributorRole); + } + + [Fact] + 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); // Act List result = _validator.TestValidate(bookCommand); @@ -384,7 +1588,7 @@ public class UpdateBookCommandValidatorTests } [Fact] - public void Validate_WhenRatingValueIsNegative_ShouldHaveValidationError() + public void Validate_WhenCalledWithNegativeRatingValue_ShouldHaveValidationError() { // Arrange UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: -1)]); @@ -395,4 +1599,147 @@ public class UpdateBookCommandValidatorTests // Assert result.ShouldHaveValidationError(Errors.Metadata.RatingValueMustBePositive); } + + [Fact] + public void Validate_WhenCalledWithRatingValueGreaterThanMaxValue_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 6, maxValue: 5)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue); + } + + [Fact] + public void Validate_WhenCalledWithNegativeMaxRatingValue_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(maxValue: -1)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingMaxValueMustBePositive); + } + + [Fact] + public void Validate_WhenCalledWithNegativeVoteCount_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(voteCount: -1)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenCalledWithValidRatings_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(value: 4, maxValue: 5, voteCount: 100)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingsListCannotBeNull); + } + + [Fact] + public void Validate_WhenCalledWithNullVoteCount_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(ratings: [_bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false)]); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); + } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCommand bookCommand = _commandBookFixture.Create(bookId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } } 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 6cab89fc..5794b4e8 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 @@ -2,7 +2,7 @@ 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.Repositories.Books; +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.UoW; @@ -12,6 +12,7 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; 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; @@ -64,6 +65,7 @@ public class UpdateBookCoverCommandHandlerTests _mockLibraryRepository = Substitute.For(); _mockMediaContributorRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); @@ -90,24 +92,24 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); - existingBook.BookArtwork = []; + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + existingBook.Artwork = []; LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); - _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal("/media/books/cover.jpg", result.Value); - Assert.Single(existingBook.BookArtwork); - Assert.Equal(ArtworkType.Cover, existingBook.BookArtwork[0].ArtworkType); - Assert.Equal(result.Value, existingBook.BookArtwork[0].FileName); - Assert.Equal(ArtworkStatus.Enriched, existingBook.BookArtwork[0].Status); + Assert.Equal("/media/books/cover.jpg", result.Value.CoverPath); + Assert.Single(existingBook.Artwork); + Assert.Equal(ArtworkType.Cover, existingBook.Artwork[0].ArtworkType); + Assert.Equal(result.Value.CoverPath, existingBook.Artwork[0].FileName); + Assert.Equal(ArtworkStatus.Enriched, existingBook.Artwork[0].Status); await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( existingBook.LibraryId, existingBook.Id, @@ -125,23 +127,23 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); - BookArtworkEntity existingCover = _bookArtworkEntityFixture.Create(bookId: command.BookId, artworkType: ArtworkType.Cover, fileName: "/media/books/old-cover.jpg"); - existingBook.BookArtwork = [existingCover]; + 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]; LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); - _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal("/media/books/cover.jpg", result.Value); - Assert.Single(existingBook.BookArtwork); - Assert.Equal(result.Value, existingCover.FileName); + Assert.Equal("/media/books/cover.jpg", result.Value.CoverPath); + Assert.Single(existingBook.Artwork); + Assert.Equal(result.Value.CoverPath, existingCover.FileName); Assert.Equal(ArtworkStatus.Enriched, existingCover.Status); Assert.Equal(_userId, existingCover.UpdatedBy); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); @@ -152,24 +154,24 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + 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"); - existingBook.BookContributors = + existingBook.Contributors = [ - _bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: author.Id, roleCategory: MediaContributorRoleCategory.Author), - _bookContributorEntityFixture.Create(bookId: command.BookId, mediaContributorId: illustrator.Id, roleCategory: MediaContributorRoleCategory.Illustrator) + _bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), mediaContributorId: author.Id, role: MediaContributorRole.Author), + _bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), mediaContributorId: illustrator.Id, role: MediaContributorRole.Illustrator) ]; LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); - _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>([author, illustrator])); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -185,37 +187,31 @@ public class UpdateBookCoverCommandHandlerTests } [Fact] - public async Task HandleAsync_WhenAuthorResolutionFails_ShouldStoreArtworkWithEmptyAuthorName() + public async Task HandleAsync_WhenAuthorResolutionFails_ShouldReturnFailureResultWithoutStoringArtwork() { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); - existingBook.BookContributors = + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); + existingBook.Contributors = [ - _bookContributorEntityFixture.Create(bookId: command.BookId, roleCategory: MediaContributorRoleCategory.Author) + _bookContributorEntityFixture.Create(bookId: Guid.Parse(command.BookId!), role: MediaContributorRole.Author) ]; LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); - _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Errors.Library.LibraryIdCannotBeEmpty); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert - Assert.False(result.IsFailure); - await _mockBookArtworkService.Received(1).SaveBookArtworkAsync( - existingBook.LibraryId, - existingBook.Id, - library.Title, - string.Empty, - existingBook.Title, - Arg.Any(), - Arg.Any(), - Arg.Any()); + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } [Fact] @@ -226,12 +222,12 @@ public class UpdateBookCoverCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookCoverCannotBeNull]); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookCoverCannotBeNull, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -243,7 +239,7 @@ public class UpdateBookCoverCommandHandlerTests _mockCurrentUserService.UserId.Returns((Guid?)null); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -256,16 +252,16 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -274,14 +270,14 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + 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)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -295,14 +291,14 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + 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)); - _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -316,21 +312,106 @@ public class UpdateBookCoverCommandHandlerTests { // Arrange UpdateBookCoverCommand command = _commandFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: command.BookId); + BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); LibraryEntity library = _libraryEntityFixture.Create(id: existingBook.LibraryId); - _mockBookRepository.GetByIdAsync(command.BookId, Arg.Any()) + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) .Returns(Result.From(existingBook)); - _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); _mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Errors.FileSystemManagement.FileTooLarge); // Act - Result result = await _sut.HandleAsync(command, CancellationToken.None); + Result result = await _sut.HandleAsync(command, CancellationToken.None); // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.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()) + .Returns(Result.From(existingBook)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenBookRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(); + _mockBookRepository.GetByIdAsync(Guid.Parse(command.BookId!), cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.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)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnFailureResultWithoutReturningTheCoverPath() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.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()) + .Returns(Result.From(existingBook)); + _mockLibraryRepository.GetByIdAsync(existingBook.LibraryId, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError); + await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(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 1e400574..8e3cfcfb 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 @@ -33,11 +33,50 @@ public class UpdateBookCoverCommandValidatorTests Assert.Empty(result); } + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(libraryId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(libraryId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + [Fact] public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() { // Arrange - UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty); + UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.Empty.ToString()); // Act List result = _validator.TestValidate(command); @@ -46,6 +85,32 @@ public class UpdateBookCoverCommandValidatorTests result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); } + [Fact] + public void Validate_WhenBookIdIsNotAGuid_ShouldHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(bookId: "not-a-guid"); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(bookId: Guid.NewGuid().ToString()); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + [Fact] public void Validate_WhenCoverIsNull_ShouldHaveValidationError() { @@ -58,4 +123,30 @@ public class UpdateBookCoverCommandValidatorTests // Assert result.ShouldHaveValidationError(Errors.WrittenContent.BookCoverCannotBeNull); } + + [Fact] + public void Validate_WhenCoverIsPresentAndFileNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCoverIsMissingAndFileNameIsEmpty_ShouldNotHaveFileNameValidationError() + { + // Arrange + UpdateBookCoverCommand command = _commandFixture.Create(fileName: string.Empty, includeCover: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.FileSystemManagement.FileNameCannotBeEmpty); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs index 7a956f9e..d9509b60 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBook/GetBookQueryHandlerTests.cs @@ -1,15 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -18,9 +15,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; 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; @@ -36,14 +31,12 @@ public class GetBookQueryHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IBookRepository _mockBookRepository; - private readonly IMediaContributorRepository _mockMediaContributorRepository; private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly GetBookQueryHandler _sut; private readonly Guid _userId; private readonly BookEntityFixture _bookEntityFixture = new(); - private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new(); private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); private readonly GetBookQueryFixture _getBookQueryFixture = new(); @@ -53,10 +46,9 @@ public class GetBookQueryHandlerTests public GetBookQueryHandlerTests() { _mockBookRepository = Substitute.For(); - _mockMediaContributorRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); - _mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); @@ -76,8 +68,10 @@ public class GetBookQueryHandlerTests { // Arrange GetBookQuery query = _getBookQueryFixture.Create(); - BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id); - _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(bookEntity)); // Act @@ -85,27 +79,27 @@ public class GetBookQueryHandlerTests // Assert Assert.False(result.IsFailure); - Assert.Equal(query.Id, result.Value.Id); + Assert.Equal(bookId, result.Value.Id); Assert.Equal(bookEntity.Title, result.Value.Metadata!.Title); - Assert.Null(result.Value.Contributors); - await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); + Assert.NotNull(result.Value.Contributors); + Assert.Empty(result.Value.Contributors!); } [Fact] - public async Task HandleAsync_WhenBookHasContributors_ShouldReturnResponseWithResolvedContributorNames() + public async Task HandleAsync_WhenBookHasContributors_ShouldReturnResponseWithContributorReferences() { // Arrange GetBookQuery query = _getBookQueryFixture.Create(); - BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id); - MediaContributorEntity contributor = _mediaContributorEntityFixture.Create(); - bookEntity.BookContributors = + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + Guid contributorId = Guid.NewGuid(); + bookEntity.Contributors = [ - _bookContributorEntityFixture.Create(bookId: query.Id, mediaContributorId: contributor.Id, roleName: "author", roleCategory: MediaContributorRoleCategory.Author) + _bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author) ]; - _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(bookEntity)); - _mockMediaContributorRepository.GetByIdsAsync(Arg.Any>(), Arg.Any()) - .Returns(Result.From>([contributor])); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -114,8 +108,8 @@ public class GetBookQueryHandlerTests Assert.False(result.IsFailure); Assert.NotNull(result.Value.Contributors); Assert.Single(result.Value.Contributors!); - Assert.Equal(contributor.DisplayName, result.Value.Contributors![0].Name!.DisplayName); - Assert.Equal("author", result.Value.Contributors![0].Role!.Name); + Assert.Equal(contributorId, result.Value.Contributors![0].ContributorId); + Assert.Equal(MediaContributorRole.Author, result.Value.Contributors![0].Role); } [Fact] @@ -123,7 +117,8 @@ public class GetBookQueryHandlerTests { // Arrange GetBookQuery query = _getBookQueryFixture.Create(); - _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -135,12 +130,32 @@ public class GetBookQueryHandlerTests await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + GetBookQuery query = _getBookQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid()); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(bookEntity)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() { // Arrange GetBookQuery query = _getBookQueryFixture.Create(); - _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Errors.Library.LibraryIdCannotBeEmpty); // Act @@ -156,8 +171,10 @@ public class GetBookQueryHandlerTests { // Arrange GetBookQuery query = _getBookQueryFixture.Create(); - BookEntity bookEntity = _bookEntityFixture.Create(id: query.Id); - _mockBookRepository.GetByIdAsync(query.Id, Arg.Any()) + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) .Returns(Result.From(bookEntity)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -170,7 +187,6 @@ public class GetBookQueryHandlerTests Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == bookEntity.LibraryId), Arg.Any()); - await _mockMediaContributorRepository.DidNotReceive().GetByIdsAsync(Arg.Any>(), Arg.Any()); } [Fact] @@ -186,7 +202,7 @@ public class GetBookQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); } @@ -203,7 +219,7 @@ public class GetBookQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); } } 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 222acdb4..dca3023a 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 @@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,7 +20,7 @@ public class GetBookQueryValidatorTests private readonly GetBookQueryValidator _validator = new(); [Fact] - public void Validate_WhenIdIsValid_ShouldNotHaveValidationError() + public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError() { // Arrange GetBookQuery query = _queryBookFixture.Create(); @@ -30,14 +29,36 @@ public class GetBookQueryValidatorTests List result = _validator.TestValidate(query); // Assert + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); } - [Fact] - public void Validate_WhenIdIsEmpty_ShouldHaveValidationError() + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) { // Arrange - GetBookQuery query = _queryBookFixture.Create(id: Guid.Empty); + GetBookQuery query = _queryBookFixture.Create() with { LibraryId = libraryId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) + { + // Arrange + GetBookQuery query = _queryBookFixture.Create() with { BookId = bookId }; // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs index b2c32756..ebf73404 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; @@ -52,6 +52,7 @@ public class GetBooksQueryHandlerTests { _mockBookRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -75,12 +76,13 @@ public class GetBooksQueryHandlerTests CancellationToken cancellationToken = CancellationToken.None; List bookEntities = _bookEntityFixture.CreateMany(2); PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -101,12 +103,13 @@ public class GetBooksQueryHandlerTests // Arrange GetBooksQuery query = _getBooksQueryFixture.Create(); PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -122,12 +125,13 @@ public class GetBooksQueryHandlerTests { // Arrange GetBooksQuery query = _getBooksQueryFixture.Create(); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Errors.Library.FilterMustIncludeLibraryId); // Act @@ -145,51 +149,55 @@ public class GetBooksQueryHandlerTests GetBooksQuery query = _getBooksQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, cancellationToken); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllAsync( Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Is(cancellationToken)); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && filter.SearchTerm == query.SearchTerm), + shouldTrackEntities: false, + cancellationToken: Arg.Is(cancellationToken)); } [Fact] public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() { // Arrange - GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending); + GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid().ToString(), sortOrder: SortOrder.Ascending); PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + shouldTrackEntities: false, + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, CancellationToken.None); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllAsync( Arg.Is(paginationData => paginationData == null), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Any()); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && filter.SearchTerm == query.SearchTerm), + shouldTrackEntities: false, + cancellationToken: Arg.Any()); } [Fact] @@ -207,8 +215,8 @@ public class GetBooksQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == query.Filter.LibraryId), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + _userId, Arg.Is(context => context.LibraryId == Guid.Parse(query.LibraryId!)), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); } [Fact] @@ -225,7 +233,7 @@ public class GetBooksQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); } [Fact] @@ -242,6 +250,6 @@ public class GetBooksQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs index 05f8e41e..8988d929 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryValidatorTests.cs @@ -24,7 +24,59 @@ public class GetBooksQueryValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty); + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsGuidEmpty_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAValidGuid_ShouldHaveValidationError() + { + // Arrange + GetBooksQuery query = _getBooksQueryFixture.Create(libraryId: "not-a-library-guid"); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs index 645a651f..f179f30b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs @@ -1,15 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; -using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Responses.Common; @@ -41,9 +41,9 @@ public class GetBooksLiteQueryHandlerTests private readonly IValidator _mockValidator; private readonly GetBooksLiteQueryHandler _sut; private readonly Guid _userId; - private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookLiteRowFixture _bookLiteRowFixture = new(); private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new(); - private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -52,6 +52,7 @@ public class GetBooksLiteQueryHandlerTests { _mockBookRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); @@ -73,14 +74,14 @@ public class GetBooksLiteQueryHandlerTests // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); - _mockBookRepository.GetPaginatedAsync( + List bookLiteRows = _bookLiteRowFixture.CreateMany(2); + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookLiteRows, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -88,7 +89,7 @@ public class GetBooksLiteQueryHandlerTests // Assert Assert.False(result.IsFailure); - Assert.Equal(bookEntities.Count, result.Value.Data.Count); + Assert.Equal(bookLiteRows.Count, result.Value.Data.Count); Assert.Equal(paginatedBooks.CurrentPage, result.Value.CurrentPage); Assert.Equal(paginatedBooks.PerPage, result.Value.PerPage); Assert.Equal(paginatedBooks.Count, result.Value.Count); @@ -100,13 +101,13 @@ public class GetBooksLiteQueryHandlerTests { // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act @@ -122,12 +123,12 @@ public class GetBooksLiteQueryHandlerTests { // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - _mockBookRepository.GetPaginatedAsync( + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Errors.Library.FilterMustIncludeLibraryId); // Act @@ -144,52 +145,58 @@ public class GetBooksLiteQueryHandlerTests // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, cancellationToken); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllLiteAsync( Arg.Is(paginationData => paginationData.CurrentPage == query.PaginationData!.CurrentPage && paginationData.PerPage == query.PaginationData.PerPage), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Is(cancellationToken)); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && + filter.SearchTerm == query.SearchTerm && + filter.FilterAlphaKey == query.FilterAlphaKey && + filter.ShouldIgnoreThePrefixForAlphaPicker == query.ShouldIgnoreThePrefixForAlphaPicker), + cancellationToken: Arg.Is(cancellationToken)); } [Fact] public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending); - PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); - _mockBookRepository.GetPaginatedAsync( + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid().ToString(), sortOrder: SortOrder.Ascending); + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); + _mockBookRepository.GetAllLiteAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any()) + cancellationToken: Arg.Any()) .Returns(Result.From(paginatedBooks)); // Act await _sut.HandleAsync(query, CancellationToken.None); // Assert - await _mockBookRepository.Received(1).GetPaginatedAsync( + await _mockBookRepository.Received(1).GetAllLiteAsync( Arg.Is(paginationData => paginationData == null), Arg.Is(query.SortBy), Arg.Is(query.SortOrder), - Arg.Is(filter => filter.LibraryId == query.Filter.LibraryId && filter.SearchTerm == query.Filter.SearchTerm), - Arg.Any()); + Arg.Is(filter => filter.LibraryId == Guid.Parse(query.LibraryId!) && + filter.SearchTerm == query.SearchTerm && + filter.FilterAlphaKey == query.FilterAlphaKey && + filter.ShouldIgnoreThePrefixForAlphaPicker == query.ShouldIgnoreThePrefixForAlphaPicker), + cancellationToken: Arg.Any()); } [Fact] @@ -207,8 +214,8 @@ public class GetBooksLiteQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( - _userId, Arg.Is(context => context.LibraryId == query.Filter.LibraryId), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + _userId, Arg.Is(context => context.LibraryId == Guid.Parse(query.LibraryId!)), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -225,7 +232,7 @@ public class GetBooksLiteQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -242,6 +249,6 @@ public class GetBooksLiteQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetAllLiteAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs index 3d9e59d8..7e739bab 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryValidatorTests.cs @@ -24,7 +24,59 @@ public class GetBooksLiteQueryValidatorTests public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() { // Arrange - GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty); + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: string.Empty); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNull_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsWhitespace_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: " "); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsGuidEmpty_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: Guid.Empty.ToString()); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotAValidGuid_ShouldHaveValidationError() + { + // Arrange + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(libraryId: "not-a-library-guid"); // Act List result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandlerTests.cs index 7dc43a29..0aab558c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryHandlerTests.cs @@ -1,7 +1,7 @@ #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.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; @@ -57,6 +57,7 @@ public class GetReadingAvailabilityQueryHandlerTests _mockBookRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockAuthorizationService = Substitute.For(); @@ -79,12 +80,14 @@ public class GetReadingAvailabilityQueryHandlerTests { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: true); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse); // Act @@ -100,12 +103,14 @@ public class GetReadingAvailabilityQueryHandlerTests { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: book.Id, libraryId: book.LibraryId, isAvailable: false, errorCode: nameof(Errors.Reading.ReaderDisabled)); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).Returns(expectedResponse); // Act @@ -122,7 +127,8 @@ public class GetReadingAvailabilityQueryHandlerTests { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(null)); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -133,14 +139,35 @@ public class GetReadingAvailabilityQueryHandlerTests await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid()); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any()).Returns(Result.From(null)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -156,8 +183,10 @@ public class GetReadingAvailabilityQueryHandlerTests { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -167,7 +196,7 @@ public class GetReadingAvailabilityQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } @@ -185,7 +214,24 @@ public class GetReadingAvailabilityQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); } [Fact] @@ -193,16 +239,16 @@ public class GetReadingAvailabilityQueryHandlerTests { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Reading.BookIdCannotBeEmpty]); + _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError); + Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockBookReadingService.DidNotReceive().GetAvailabilityAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidatorTests.cs index db707d8a..c272fccc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingAvailability/GetReadingAvailabilityQueryValidatorTests.cs @@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,20 +20,7 @@ public class GetReadingAvailabilityQueryValidatorTests private readonly GetReadingAvailabilityQueryFixture _getReadingAvailabilityQueryFixture = new(); [Fact] - public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(bookId: Guid.Empty); - - // Act - List result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() + public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError() { // Arrange GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create(); @@ -43,6 +29,41 @@ public class GetReadingAvailabilityQueryValidatorTests List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create() with { LibraryId = libraryId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) + { + // Arrange + GetReadingAvailabilityQuery query = _getReadingAvailabilityQueryFixture.Create() with { BookId = bookId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandlerTests.cs index 3226ffa8..23974582 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryHandlerTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -63,6 +63,7 @@ public class GetReadingManifestQueryHandlerTests _mockLibraryRepository = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); @@ -87,12 +88,14 @@ public class GetReadingManifestQueryHandlerTests { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create(); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse); // Act @@ -108,14 +111,16 @@ public class GetReadingManifestQueryHandlerTests { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true); ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create(); _mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From(settings)); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse); // Act @@ -131,7 +136,8 @@ public class GetReadingManifestQueryHandlerTests { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(null)); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -142,14 +148,35 @@ public class GetReadingManifestQueryHandlerTests await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid()); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any()).Returns(Result.From(null)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -165,8 +192,10 @@ public class GetReadingManifestQueryHandlerTests { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -176,7 +205,7 @@ public class GetReadingManifestQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } @@ -194,7 +223,24 @@ public class GetReadingManifestQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); } [Fact] @@ -202,16 +248,16 @@ public class GetReadingManifestQueryHandlerTests { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); - _mockValidator.Validate(Arg.Any()).Returns([Errors.Reading.BookIdCannotBeEmpty]); + _mockValidator.Validate(Arg.Any()).Returns([Errors.WrittenContent.BookIdCannotBeEmpty]); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); // Assert Assert.True(result.IsFailure); - Assert.Equal(Errors.Reading.BookIdCannotBeEmpty, result.FirstError); + Assert.Equal(Errors.WrittenContent.BookIdCannotBeEmpty, result.FirstError); await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockBookReadingService.DidNotReceive().GetManifestAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidatorTests.cs index 8bb06c0d..4434a44e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingManifest/GetReadingManifestQueryValidatorTests.cs @@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,20 +20,7 @@ public class GetReadingManifestQueryValidatorTests private readonly GetReadingManifestQueryFixture _getReadingManifestQueryFixture = new(); [Fact] - public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(bookId: Guid.Empty); - - // Act - List result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError() + public void Validate_WhenIdsAreValid_ShouldNotHaveValidationError() { // Arrange GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create(); @@ -43,6 +29,41 @@ public class GetReadingManifestQueryValidatorTests List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create() with { LibraryId = libraryId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) + { + // Arrange + GetReadingManifestQuery query = _getReadingManifestQueryFixture.Create() with { BookId = bookId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandlerTests.cs index ec4e21ba..51f16a84 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryHandlerTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -63,6 +63,7 @@ public class GetReadingResourceQueryHandlerTests _mockLibraryRepository = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); @@ -87,12 +88,14 @@ public class GetReadingResourceQueryHandlerTests { // Arrange GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create(); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: false, cancellationToken).Returns(expectedResponse); // Act @@ -108,14 +111,16 @@ public class GetReadingResourceQueryHandlerTests { // Arrange GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true); ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create(); _mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From(settings)); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages: true, cancellationToken).Returns(expectedResponse); // Act @@ -131,7 +136,8 @@ public class GetReadingResourceQueryHandlerTests { // Arrange GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(null)); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -142,14 +148,35 @@ public class GetReadingResourceQueryHandlerTests await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid()); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() { // Arrange GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any()).Returns(Result.From(null)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -165,8 +192,10 @@ public class GetReadingResourceQueryHandlerTests { // Arrange GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -192,7 +221,24 @@ public class GetReadingResourceQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); } [Fact] @@ -208,7 +254,7 @@ public class GetReadingResourceQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Reading.ResourceKeyCannotBeEmpty, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockBookReadingService.DidNotReceive().GetResourceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidatorTests.cs index ecf24f05..d2101616 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingResource/GetReadingResourceQueryValidatorTests.cs @@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -20,32 +19,6 @@ public class GetReadingResourceQueryValidatorTests private readonly GetReadingResourceQueryValidator _validator = new(); private readonly GetReadingResourceQueryFixture _getReadingResourceQueryFixture = new(); - [Fact] - public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(bookId: Guid.Empty); - - // Act - List result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create(resourceKey: string.Empty); - - // Act - List result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty); - } - [Fact] public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() { @@ -56,7 +29,57 @@ public class GetReadingResourceQueryValidatorTests List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); result.ShouldNotHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty); } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { LibraryId = libraryId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) + { + // Arrange + GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { BookId = bookId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + public void Validate_WhenResourceKeyIsEmpty_ShouldHaveValidationError(string? resourceKey) + { + // Arrange + GetReadingResourceQuery query = _getReadingResourceQueryFixture.Create() with { ResourceKey = resourceKey }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Reading.ResourceKeyCannotBeEmpty); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandlerTests.cs index 4dc361ea..5def93e7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryHandlerTests.cs @@ -2,7 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; @@ -63,6 +63,7 @@ public class GetReadingSectionQueryHandlerTests _mockLibraryRepository = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); @@ -87,12 +88,14 @@ public class GetReadingSectionQueryHandlerTests { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: false, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse); // Act @@ -108,14 +111,16 @@ public class GetReadingSectionQueryHandlerTests { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: true, shouldPreserveBookStyles: true); ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef); _mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From(settings)); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages: true, shouldPreserveStyles: true, cancellationToken).Returns(expectedResponse); // Act @@ -133,14 +138,16 @@ public class GetReadingSectionQueryHandlerTests { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: _userId, shouldRenderPdfAsImages: false, shouldPreserveBookStyles: shouldPreserveBookStyles); ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef); _mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationToken).Returns(Result.From(settings)); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetSectionAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(expectedResponse); // Act @@ -157,12 +164,14 @@ public class GetReadingSectionQueryHandlerTests { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); CancellationToken cancellationToken = CancellationToken.None; - BookEntity book = _bookEntityFixture.Create(id: query.BookId); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); LibraryEntity library = _libraryEntityFixture.Create(id: book.LibraryId, libraryType: LibraryType.EBook); ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: query.LocationRef); - _mockBookRepository.GetByIdAsync(query.BookId, cancellationToken).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).Returns(Result.From(library)); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).Returns(Result.From(library)); _mockBookReadingService.GetSectionAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(expectedResponse); // Act @@ -180,7 +189,8 @@ public class GetReadingSectionQueryHandlerTests { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(null)); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -191,14 +201,35 @@ public class GetReadingSectionQueryHandlerTests await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundError() + { + // Arrange + GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid()); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Reading.BookNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError() { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); - _mockLibraryRepository.GetByIdAsync(book.LibraryId, Arg.Any()).Returns(Result.From(null)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); + _mockLibraryRepository.GetByIdAsync(book.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(null)); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -214,8 +245,10 @@ public class GetReadingSectionQueryHandlerTests { // Arrange GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); - BookEntity book = _bookEntityFixture.Create(id: query.BookId); - _mockBookRepository.GetByIdAsync(query.BookId, Arg.Any()).Returns(Result.From(book)); + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid bookId = Guid.Parse(query.BookId!); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()).Returns(Result.From(book)); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(false); @@ -241,7 +274,24 @@ public class GetReadingSectionQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult() + { + // Arrange + GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(); + Guid bookId = Guid.Parse(query.BookId!); + _mockBookRepository.GetByIdAsync(bookId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Errors.Library.LibraryIdCannotBeEmpty); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError); } [Fact] @@ -257,7 +307,7 @@ public class GetReadingSectionQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Reading.LocationRefCannotBeEmpty, result.FirstError); - await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), shouldTrackEntities: false, cancellationToken: Arg.Any()); await _mockBookReadingService.DidNotReceive().GetSectionAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidatorTests.cs index 1555f5d7..d6d1f5db 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/Queries/GetReadingSection/GetReadingSectionQueryValidatorTests.cs @@ -4,7 +4,6 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLi using Lumina.Application.UnitTests.Common.Setup; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -20,32 +19,6 @@ public class GetReadingSectionQueryValidatorTests private readonly GetReadingSectionQueryValidator _validator = new(); private readonly GetReadingSectionQueryFixture _getReadingSectionQueryFixture = new(); - [Fact] - public void Validate_WhenBookIdIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(bookId: Guid.Empty); - - // Act - List result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); - } - - [Fact] - public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError() - { - // Arrange - GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create(locationRef: string.Empty); - - // Act - List result = _validator.TestValidate(query); - - // Assert - result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty); - } - [Fact] public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError() { @@ -56,7 +29,57 @@ public class GetReadingSectionQueryValidatorTests List result = _validator.TestValidate(query); // Assert - result.ShouldNotHaveValidationError(Errors.Reading.BookIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); result.ShouldNotHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty); } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId) + { + // Arrange + GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { LibraryId = libraryId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData("not-a-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId) + { + // Arrange + GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { BookId = bookId }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + public void Validate_WhenLocationRefIsEmpty_ShouldHaveValidationError(string? locationRef) + { + // Arrange + GetReadingSectionQuery query = _getReadingSectionQueryFixture.Create() with { LocationRef = locationRef }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Reading.LocationRefCannotBeEmpty); + } } 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 b733d3e8..032fc332 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 @@ -44,6 +44,7 @@ public class ReorderLibraryArtworkProvidersCommandHandlerTests public ReorderLibraryArtworkProvidersCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); 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 a26e0808..c21aa390 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 @@ -44,6 +44,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests public ReorderLibraryMetadataProvidersCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs index 8d6e2260..246bf924 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class SetLibraryArtworkProviderEnabledCommandHandlerTests public SetLibraryArtworkProviderEnabledCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); 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 bb131916..7b838254 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 @@ -45,6 +45,7 @@ public class SetLibraryBookReaderEnabledCommandHandlerTests public SetLibraryBookReaderEnabledCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryBookReaderConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index 2fa3c5a7..d53f845c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests public SetLibraryMetadataProviderEnabledCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index d2b3ee7e..3dce9d21 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -34,6 +34,7 @@ public class UpdatePluginSettingsCommandHandlerTests public UpdatePluginSettingsCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockValidator = Substitute.For>(); 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 052052ba..6b90b6d9 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -47,6 +49,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests public GetLibraryArtworkProvidersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockArtworkProviderConfigurationRepository = Substitute.For(); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); @@ -100,7 +103,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests _pluginEntityFixture.Create(firstPluginId), _pluginEntityFixture.Create(secondPluginId) ]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -127,8 +131,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests ]; _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([_pluginEntityFixture.Create()])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -147,8 +151,8 @@ public class GetLibraryArtworkProvidersQueryHandlerTests GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -172,7 +176,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -182,7 +186,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act @@ -209,7 +213,7 @@ public class GetLibraryArtworkProvidersQueryHandlerTests await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] 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 a526618e..3a20d7dd 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -49,6 +51,7 @@ public class GetLibraryBookReadersQueryHandlerTests public GetLibraryBookReadersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryBookReaderConfigurationRepository = Substitute.For(); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository); @@ -104,7 +107,8 @@ public class GetLibraryBookReadersQueryHandlerTests _pluginEntityFixture.Create(enabledPluginId, "A Reader"), _pluginEntityFixture.Create(disabledPluginId, "B Reader") ]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); Dictionary> supportedExtensions = new() { [enabledPluginId] = [".epub"], @@ -138,8 +142,8 @@ public class GetLibraryBookReadersQueryHandlerTests ]; _mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([_pluginEntityFixture.Create()])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -159,8 +163,8 @@ public class GetLibraryBookReadersQueryHandlerTests GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create(); _mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -184,7 +188,7 @@ public class GetLibraryBookReadersQueryHandlerTests // Assert Assert.True(result.IsFailure); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -194,7 +198,7 @@ public class GetLibraryBookReadersQueryHandlerTests GetLibraryBookReadersQuery query = _getLibraryBookReadersQueryFixture.Create(); _mockLibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act @@ -219,7 +223,7 @@ public class GetLibraryBookReadersQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] 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 16e3965f..6c456d79 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; @@ -48,6 +50,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests public GetLibraryMetadataProvidersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockAuthorizationService = Substitute.For(); @@ -100,7 +103,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _pluginEntityFixture.Create(firstPluginId), _pluginEntityFixture.Create(secondPluginId) ]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -127,8 +131,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests ]; _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([_pluginEntityFixture.Create()])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [_pluginEntityFixture.Create()], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -147,8 +151,8 @@ public class GetLibraryMetadataProvidersQueryHandlerTests GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -172,7 +176,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -182,7 +186,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act @@ -209,7 +213,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any(), Arg.Any()); - await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs index db3a2b55..835bf264 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs @@ -45,6 +45,7 @@ public class GetPluginSettingsQueryHandlerTests public GetPluginSettingsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockPluginManager = Substitute.For(); @@ -67,7 +68,7 @@ public class GetPluginSettingsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Plugins.PluginIdCannotBeEmpty, result.FirstError); - await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -76,7 +77,7 @@ public class GetPluginSettingsQueryHandlerTests // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); PluginEntity plugin = _pluginEntityFixture.Create(query.PluginId); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(Result.From(plugin)); IPlugin loadedPlugin = Substitute.For(); @@ -107,7 +108,7 @@ public class GetPluginSettingsQueryHandlerTests // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); PluginEntity plugin = _pluginEntityFixture.Create(query.PluginId); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(Result.From(plugin)); _mockPluginManager.GetPlugin(query.PluginId).Returns((IPlugin?)null); @@ -125,7 +126,7 @@ public class GetPluginSettingsQueryHandlerTests { // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -143,7 +144,7 @@ public class GetPluginSettingsQueryHandlerTests // Arrange GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); Error error = Error.Failure(description: "Failed to get plugin"); - _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(query.PluginId, cancellationToken: Arg.Any()) .Returns(error); // Act 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 45bd8263..e1387496 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +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.Core.Plugins.Queries.GetPlugins; @@ -34,6 +36,7 @@ public class GetPluginsQueryHandlerTests public GetPluginsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _sut = new GetPluginsQueryHandler(_mockUnitOfWork); @@ -44,7 +47,8 @@ public class GetPluginsQueryHandlerTests { // Arrange List plugins = [_pluginEntityFixture.Create(), _pluginEntityFixture.Create()]; - _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = plugins, CurrentPage = 1, PerPage = plugins.Count, Count = plugins.Count, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); @@ -60,7 +64,7 @@ public class GetPluginsQueryHandlerTests public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError() { // Arrange - _mockPluginRepository.GetAllAsync(Arg.Any()) + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs index 1ba576bb..3c2ce017 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/AddScheduledJob/AddScheduledJobCommandHandlerTests.cs @@ -49,6 +49,7 @@ public class AddScheduledJobCommandHandlerTests public AddScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs index 14effc81..3ca228e1 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/FireScheduledJob/FireScheduledJobCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class FireScheduledJobCommandHandlerTests public FireScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -72,7 +73,7 @@ public class FireScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -98,7 +99,7 @@ public class FireScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); } @@ -115,7 +116,7 @@ public class FireScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -131,7 +132,7 @@ public class FireScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -140,7 +141,7 @@ public class FireScheduledJobCommandHandlerTests // Arrange FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()).Returns(error); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -156,7 +157,7 @@ public class FireScheduledJobCommandHandlerTests { // Arrange FireScheduledJobCommand command = _fireScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -179,7 +180,7 @@ public class FireScheduledJobCommandHandlerTests scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 99, minute: 0); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -199,7 +200,7 @@ public class FireScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs index 93a48823..1f702fa3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/RemoveScheduledJob/RemoveScheduledJobCommandHandlerTests.cs @@ -51,6 +51,7 @@ public class RemoveScheduledJobCommandHandlerTests public RemoveScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -78,7 +79,7 @@ public class RemoveScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) .Returns(Result.Success); @@ -113,7 +114,7 @@ public class RemoveScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockScheduledJobRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); } @@ -130,7 +131,7 @@ public class RemoveScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -146,7 +147,7 @@ public class RemoveScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -154,7 +155,7 @@ public class RemoveScheduledJobCommandHandlerTests { // Arrange RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -175,7 +176,7 @@ public class RemoveScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to delete the executions"); _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) @@ -200,7 +201,7 @@ public class RemoveScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobExecutionRepository.DeleteByScheduledJobIdAsync(command.ScheduledJobId, Arg.Any()) .Returns(Result.Success); @@ -223,7 +224,7 @@ public class RemoveScheduledJobCommandHandlerTests // Arrange RemoveScheduledJobCommand command = _removeScheduledJobCommandFixture.Create(); Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(repositoryError); // Act @@ -247,7 +248,7 @@ public class RemoveScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(invalidScheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs index 453cc88f..538c9dbb 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StartScheduledJob/StartScheduledJobCommandHandlerTests.cs @@ -48,6 +48,7 @@ public class StartScheduledJobCommandHandlerTests public StartScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -72,7 +73,7 @@ public class StartScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -102,7 +103,7 @@ public class StartScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -119,7 +120,7 @@ public class StartScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -135,7 +136,7 @@ public class StartScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -143,7 +144,7 @@ public class StartScheduledJobCommandHandlerTests { // Arrange StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -164,7 +165,7 @@ public class StartScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -186,7 +187,7 @@ public class StartScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); @@ -207,7 +208,7 @@ public class StartScheduledJobCommandHandlerTests // Arrange StartScheduledJobCommand command = _startScheduledJobCommandFixture.Create(); Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(repositoryError); // Act @@ -230,7 +231,7 @@ public class StartScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(invalidScheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs index 7c1d40e1..0ea40450 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/StopScheduledJob/StopScheduledJobCommandHandlerTests.cs @@ -50,6 +50,7 @@ public class StopScheduledJobCommandHandlerTests public StopScheduledJobCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); @@ -75,7 +76,7 @@ public class StopScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -105,7 +106,7 @@ public class StopScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Running, lastStartedOnUtc: DateTime.UtcNow.AddMinutes(-10)); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -132,7 +133,7 @@ public class StopScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Scheduling.ScheduledJobNotFound, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); await _mockScheduledJobScheduler.DidNotReceive().StopCycleAsync(Arg.Any(), Arg.Any()); } @@ -149,7 +150,7 @@ public class StopScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -165,7 +166,7 @@ public class StopScheduledJobCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -173,7 +174,7 @@ public class StopScheduledJobCommandHandlerTests { // Arrange StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -194,7 +195,7 @@ public class StopScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Added); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -216,7 +217,7 @@ public class StopScheduledJobCommandHandlerTests id: command.ScheduledJobId, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(DomainErrors.Scheduling.ScheduledJobNotFound); @@ -237,7 +238,7 @@ public class StopScheduledJobCommandHandlerTests // Arrange StopScheduledJobCommand command = _stopScheduledJobCommandFixture.Create(); Error repositoryError = DomainErrors.Scheduling.ScheduledJobNotFound; - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(repositoryError); // Act @@ -260,7 +261,7 @@ public class StopScheduledJobCommandHandlerTests scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(command.ScheduledJobId, cancellationToken: Arg.Any()) .Returns(Result.From(invalidScheduledJob)); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs index 56b302ff..3e579bc9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Commands/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesCommandHandlerTests.cs @@ -41,6 +41,7 @@ public class UpdateSchedulerDisplayPreferencesCommandHandlerTests public UpdateSchedulerDisplayPreferencesCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockSchedulerDisplayPreferencesRepository = Substitute.For(); 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 a26df0e4..bcb83c98 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobAddedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -40,11 +42,12 @@ public class ScheduledJobAddedDomainEventHandlerTests public ScheduledJobAddedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobAddedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -56,7 +59,7 @@ public class ScheduledJobAddedDomainEventHandlerTests ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([scheduledJob1, scheduledJob2])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [scheduledJob1, scheduledJob2], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -73,7 +76,7 @@ public class ScheduledJobAddedDomainEventHandlerTests // Arrange ScheduledJobAddedDomainEvent domainEvent = _scheduledJobAddedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( 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 1a19fd47..247f2aaa 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStartedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.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.Core.Scheduling.Events; using Lumina.Application.Core.Scheduling.Notifications; @@ -39,12 +41,13 @@ public class ScheduledJobCycleStartedDomainEventHandlerTests public ScheduledJobCycleStartedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobScheduler = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobCycleStartedDomainEventHandler(_mockScheduledJobNotifier, _mockScheduledJobScheduler, _mockUnitOfWork); } @@ -69,7 +72,7 @@ public class ScheduledJobCycleStartedDomainEventHandlerTests // Arrange ScheduledJobCycleStartedDomainEvent domainEvent = _scheduledJobCycleStartedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( 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 2de58f22..79a52e25 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobCycleStoppedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -39,11 +41,12 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests public ScheduledJobCycleStoppedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobCycleStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -54,7 +57,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(Arg.Any()).Returns(Result.From>([stoppedJob])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [stoppedJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -71,7 +74,7 @@ public class ScheduledJobCycleStoppedDomainEventHandlerTests // Arrange ScheduledJobCycleStoppedDomainEvent domainEvent = _scheduledJobCycleStoppedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( 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 9f0ef999..58f87229 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionCompletedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -43,6 +45,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests public ScheduledJobExecutionCompletedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); @@ -51,7 +54,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(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobExecutionCompletedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -68,14 +71,14 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running, lastStartedOnUtc: completedOnUtc.AddMinutes(-5)); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create( id: domainEvent.RunId, scheduledJobId: scheduledJob.Id, isCycleRun: isCycleRun, completedOnUtc: null); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(execution)); // Act @@ -100,7 +103,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests { // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -109,7 +112,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Assert Assert.Equal(Errors.Scheduling.ScheduledJobNotFound, exception.EventualConsistencyError); - await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -118,7 +121,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to update the scheduled job"); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -129,7 +132,7 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockScheduledJobExecutionRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -138,9 +141,9 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -158,10 +161,10 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(execution)); Error error = Error.Failure("Database.Error", "Failed to update the execution"); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -181,13 +184,13 @@ public class ScheduledJobExecutionCompletedDomainEventHandlerTests // Arrange ScheduledJobExecutionCompletedDomainEvent domainEvent = _scheduledJobExecutionCompletedDomainEventFixture.Create(isCycleRun: true); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Running); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); ScheduledJobExecutionEntity execution = _scheduledJobExecutionEntityFixture.Create(id: domainEvent.RunId); - _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, Arg.Any()) + _mockScheduledJobExecutionRepository.GetByIdAsync(domainEvent.RunId, cancellationToken: Arg.Any()) .Returns(Result.From(execution)); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( 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 8613b765..7c453083 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStartedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -44,6 +46,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests public ScheduledJobExecutionStartedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); @@ -52,7 +55,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(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobExecutionStartedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -68,7 +71,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests taskType: domainEvent.TaskType, scheduleType: ScheduleType.WithIntervalInMinutes, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); // Act @@ -100,7 +103,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( @@ -116,7 +119,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests { // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -135,7 +138,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create( id: domainEvent.ScheduledJobId.Value, status: ScheduledJobStatus.Active); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to update the scheduled job"); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -155,7 +158,7 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to insert the execution"); _mockScheduledJobExecutionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(error); @@ -175,10 +178,10 @@ public class ScheduledJobExecutionStartedDomainEventHandlerTests // Arrange ScheduledJobExecutionStartedDomainEvent domainEvent = _scheduledJobExecutionStartedDomainEventFixture.Create(); ScheduledJobEntity scheduledJob = _scheduledJobEntityFixture.Create(id: domainEvent.ScheduledJobId.Value); - _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(domainEvent.ScheduledJobId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(scheduledJob)); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( 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 52c0b749..9daedcc6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobExecutionStoppedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -40,6 +42,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests public ScheduledJobExecutionStoppedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); @@ -47,7 +50,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobExecutionStoppedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -140,7 +143,7 @@ public class ScheduledJobExecutionStoppedDomainEventHandlerTests _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(domainEvent.ScheduledJobId.Value, Arg.Any()) .Returns(Result.From(null)); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( 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 54ed5c7c..689fdd5d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Events/ScheduledJobRemovedDomainEventHandlerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -39,11 +41,12 @@ public class ScheduledJobRemovedDomainEventHandlerTests public ScheduledJobRemovedDomainEventHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobNotifier = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _sut = new ScheduledJobRemovedDomainEventHandler(_mockScheduledJobNotifier, _mockUnitOfWork); } @@ -54,7 +57,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests // Arrange ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); ScheduledJobEntity remainingJob = _scheduledJobEntityFixture.Create(name: "Remaining job"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(Result.From>([remainingJob])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [remainingJob], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act await _sut.HandleAsync(domainEvent, CancellationToken.None); @@ -71,7 +74,7 @@ public class ScheduledJobRemovedDomainEventHandlerTests // Arrange ScheduledJobRemovedDomainEvent domainEvent = _scheduledJobRemovedDomainEventFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act EventualConsistencyException exception = await Assert.ThrowsAsync( diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs index 45ed8366..94966872 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetScheduledJobHistory/GetScheduledJobHistoryQueryHandlerTests.cs @@ -42,6 +42,7 @@ public class GetScheduledJobHistoryQueryHandlerTests public GetScheduledJobHistoryQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockScheduledJobExecutionRepository = Substitute.For(); 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 146499ae..a3f47aaf 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Scheduling.Queries.GetScheduledJobs; @@ -40,6 +42,7 @@ public class GetScheduledJobsQueryHandlerTests public GetScheduledJobsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockScheduledJobRepository = Substitute.For(); @@ -57,8 +60,8 @@ public class GetScheduledJobsQueryHandlerTests // Arrange ScheduledJobEntity scheduledJob1 = _scheduledJobEntityFixture.Create(name: "Job 1"); ScheduledJobEntity scheduledJob2 = _scheduledJobEntityFixture.Create(name: "Job 2"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([scheduledJob1, scheduledJob2])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [scheduledJob1, scheduledJob2], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); @@ -74,8 +77,8 @@ public class GetScheduledJobsQueryHandlerTests public async Task HandleAsync_WhenNoScheduledJobsExist_ShouldReturnEmptyCollection() { // Arrange - _mockScheduledJobRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); @@ -97,7 +100,7 @@ public class GetScheduledJobsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -112,7 +115,7 @@ public class GetScheduledJobsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); - await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -120,7 +123,7 @@ public class GetScheduledJobsQueryHandlerTests { // Arrange Error error = Error.Failure("Database.Error", "Failed to get the scheduled jobs"); - _mockScheduledJobRepository.GetAllAsync(Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(error); // Act Result> result = await _sut.HandleAsync(new GetScheduledJobsQuery(), CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs index 4fa22ff1..fd00b036 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Scheduling/Queries/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesQueryHandlerTests.cs @@ -42,6 +42,7 @@ public class GetSchedulerDisplayPreferencesQueryHandlerTests public GetSchedulerDisplayPreferencesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockSchedulerDisplayPreferencesRepository = Substitute.For(); 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 f0d763af..acbe0343 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Themes; @@ -47,6 +49,7 @@ public class DeleteThemeCommandHandlerTests public DeleteThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); @@ -185,7 +188,7 @@ public class DeleteThemeCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to get all themes"); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -206,8 +209,8 @@ public class DeleteThemeCommandHandlerTests ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, userTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, userTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -228,8 +231,8 @@ public class DeleteThemeCommandHandlerTests ThemeEntity theme = _themeEntityFixture.Create(themeId: command.ThemeId, installSource: ThemeInstallSource.Uploaded, isCurrent: true, includeIsCurrent: true, isDeleted: false); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(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 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -251,8 +254,8 @@ public class DeleteThemeCommandHandlerTests ThemeEntity otherBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, otherBundledTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, otherBundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -278,8 +281,8 @@ public class DeleteThemeCommandHandlerTests ThemeEntity bundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(Result.Deleted); @@ -304,8 +307,8 @@ public class DeleteThemeCommandHandlerTests Error error = Error.Failure("Database.Error", "Failed to delete theme"); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, bundledTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.DeleteByIdAsync(theme.Id, Arg.Any()) .Returns(error); @@ -329,8 +332,8 @@ public class DeleteThemeCommandHandlerTests _mockThemeService.DefaultThemeId.Returns(replacementTheme.ThemeId); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, replacementTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, replacementTheme], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -360,8 +363,8 @@ public class DeleteThemeCommandHandlerTests _mockThemeService.DefaultThemeId.Returns("no-such-default"); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, betaTheme, alphaTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [theme, betaTheme, alphaTheme], CurrentPage = 1, PerPage = 3, Count = 3, NumberOfPages = 1 })); _mockThemeRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -388,8 +391,8 @@ public class DeleteThemeCommandHandlerTests Error error = Error.Failure("Theme.DeleteFailed", "Failed to delete theme files"); _mockThemeRepository.GetByThemeIdAsync(command.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([theme, bundledTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { 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/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs index 833c6414..c202cf56 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/InstallTheme/InstallThemeCommandHandlerTests.cs @@ -51,6 +51,7 @@ public class InstallThemeCommandHandlerTests public InstallThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs index 0a3ffd43..f8dcab50 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/RestoreTheme/RestoreThemeCommandHandlerTests.cs @@ -45,6 +45,7 @@ public class RestoreThemeCommandHandlerTests public RestoreThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs index f63854be..9dcaa379 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Commands/SetCurrentTheme/SetCurrentThemeCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class SetCurrentThemeCommandHandlerTests public SetCurrentThemeCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockAuthorizationService = Substitute.For(); _mockValidator = Substitute.For>(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs index abb8cead..4185e99b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetCurrentTheme/GetCurrentThemeQueryHandlerTests.cs @@ -35,6 +35,7 @@ public class GetCurrentThemeQueryHandlerTests public GetCurrentThemeQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); _sut = new GetCurrentThemeQueryHandler(_mockUnitOfWork); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs index 2958bb72..4aff40af 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs @@ -41,6 +41,7 @@ public class GetThemeArchiveQueryHandlerTests public GetThemeArchiveQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockValidator = Substitute.For>(); _mockThemeRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs index c3dfd888..50e10124 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs @@ -42,6 +42,7 @@ public class GetThemeAssetQueryHandlerTests public GetThemeAssetQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockValidator = Substitute.For>(); _mockThemeRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs index 320395bf..235592d4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeTemplate/GetThemeTemplateQueryHandlerTests.cs @@ -44,6 +44,7 @@ public class GetThemeTemplateQueryHandlerTests public GetThemeTemplateQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeService = Substitute.For(); _mockValidator = Substitute.For>(); _mockThemeRepository = Substitute.For(); 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 a6e2b80c..bf076d7e 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +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.Core.Themes.Management.Queries.GetThemes; @@ -35,6 +37,7 @@ public class GetThemesQueryHandlerTests public GetThemesQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); _sut = new GetThemesQueryHandler(_mockUnitOfWork); @@ -49,8 +52,8 @@ public class GetThemesQueryHandlerTests ThemeEntity bundledLowerTheme = _themeEntityFixture.Create(themeId: "bundled-lower", name: "apple", installSource: ThemeInstallSource.Bundled, isDeleted: false); 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(Arg.Any()) - .Returns(Result.From>([uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [uploadedTheme, bundledLowerTheme, bundledUpperTheme, deletedTheme], CurrentPage = 1, PerPage = 4, Count = 4, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -73,8 +76,8 @@ public class GetThemesQueryHandlerTests { // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From>([])); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result> result = await _sut.HandleAsync(query, CancellationToken.None); @@ -90,7 +93,7 @@ public class GetThemesQueryHandlerTests // Arrange GetThemesQuery query = _getThemesQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to get all themes"); - _mockThemeRepository.GetAllAsync(Arg.Any()) + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act 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 e38e7cc4..9cf3f7ee 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 @@ -36,6 +36,7 @@ public class ChangePasswordCommandHandlerTests public ChangePasswordCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockUserRepository = Substitute.For(); 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 e542116a..91a0a558 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 @@ -39,6 +39,7 @@ public class RecoverPasswordCommandHandlerTests public RecoverPasswordCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); _mockCryptographyService = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs index 7818ddbb..d639f62f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authentication/Commands/RegisterUser/RegisterUserCommandHandlerTests.cs @@ -44,6 +44,7 @@ public class RegisterUserCommandHandlerTests public RegisterUserCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockCryptographyService = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); 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 4685623b..85c6267e 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -42,6 +44,7 @@ public class GetUsersQueryHandlerTests public GetUsersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -70,7 +73,7 @@ public class GetUsersQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -87,7 +90,7 @@ public class GetUsersQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await _mockUserRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -99,7 +102,7 @@ public class GetUsersQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -115,13 +118,13 @@ public class GetUsersQueryHandlerTests { // Arrange GetUsersQuery query = _getUsersQueryFixture.Create(); - IEnumerable users = _userEntityFixture.CreateMany(2); + List users = _userEntityFixture.CreateMany(2); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(users)); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { 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 2d372046..2d2d6761 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 @@ -42,6 +42,7 @@ public class LoginUserQueryHandlerTests public LoginUserQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockHashService = Substitute.For(); _mockJwtTokenGenerator = Substitute.For(); _mockTotpTokenGenerator = Substitute.For(); 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 0eec39ab..11888a15 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 @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; @@ -39,6 +41,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests private readonly IUserRepository _mockUserRepository; private readonly IRoleRepository _mockRoleRepository; private readonly IPermissionRepository _mockPermissionRepository; + private readonly IValidator _mockValidator; private readonly UpdateUserRoleAndPermissionsCommandHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); private readonly RoleEntityFixture _roleEntityFixture = new(); @@ -54,6 +57,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests public UpdateUserRoleAndPermissionsCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -66,14 +70,14 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockUnitOfWork.RoleRepository.Returns(_mockRoleRepository); _mockUnitOfWork.PermissionRepository.Returns(_mockPermissionRepository); - IValidator mockValidator = Substitute.For>(); - mockValidator.Validate(Arg.Any()) + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) .Returns([]); _sut = new UpdateUserRoleAndPermissionsCommandHandler( _mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, - mockValidator); + _mockValidator); } [Fact] @@ -107,7 +111,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -117,7 +121,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns((UserEntity?)null); // Act @@ -137,9 +141,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns((RoleEntity?)null); // Act @@ -167,16 +171,16 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests includeUserRole: true); RoleEntity newRole = _roleEntityFixture.Create(roleName: "User"); - IEnumerable users = [user]; + List users = [user]; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(newRole); - _mockUserRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From(users)); + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = users, CurrentPage = 1, PerPage = users.Count, Count = users.Count, NumberOfPages = 1 })); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -199,9 +203,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(role); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(Result.From(permissions)); @@ -237,9 +241,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(role); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(Result.From(permissions)); @@ -276,11 +280,11 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(_roleEntityFixture.Create(roleName: "User")); - _mockUserRepository.GetAllAsync(Arg.Any()) + _mockUserRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(error); // Act @@ -301,9 +305,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) .Returns(user); - _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) .Returns(_roleEntityFixture.Create(roleName: "User")); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(error); @@ -315,4 +319,98 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); } + + [Fact] + public async Task HandleAsync_WhenRoleIdIsOmitted_ShouldPreserveTheCurrentRole() + { + // Arrange + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: null); + RoleEntity currentRole = _roleEntityFixture.Create(roleName: "Editor"); + UserRoleEntity userRole = _userRoleEntityFixture.Create(userId: command.UserId, role: currentRole); + UserEntity user = _userEntityFixture.Create( + id: command.UserId, + username: "testUser", + password: "hashedPassword", + userRole: userRole, + includeUserRole: true); + IEnumerable permissions = command.Permissions.Select(permissionId => + _permissionEntityFixture.Create(id: permissionId, permissionName: AuthorizationPermission.CanViewUsers)); + + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) + .Returns(user); + _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) + .Returns(Result.From(permissions)); + _mockUserRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(currentRole.RoleName, result.Value.Role); + + // The current role is left untouched, so the repository is asked to keep it and no role lookup is made. + await _mockUserRepository.Received(1).UpdateAsync( + Arg.Is(updatedUser => updatedUser.UserRole != null && updatedUser.UserRole.RoleId == currentRole.Id), + Arg.Any()); + await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPermissionDoesNotExist_ShouldReturnPermissionNotFoundError() + { + // Arrange + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); + UserEntity user = _userEntityFixture.Create(id: command.UserId, username: "testUser", password: "hashedPassword"); + RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole"); + + // Only one of the requested permissions exists, so resolving the rest would throw if it were done with a strict lookup. + IEnumerable existingPermissions = + [ + _permissionEntityFixture.Create(id: command.Permissions[0], permissionName: AuthorizationPermission.CanViewUsers) + ]; + + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) + .Returns(true); + _mockUserRepository.GetByIdAsync(command.UserId, cancellationToken: Arg.Any()) + .Returns(user); + _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, cancellationToken: Arg.Any()) + .Returns(role); + _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) + .Returns(Result.From(existingPermissions)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.PermissionNotFound, result.FirstError); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnTheValidationErrorsWithoutPersisting() + { + // Arrange + UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(); + Error validationError = Error.Validation("General.Validation", "RoleIdCannotBeEmpty"); + _mockValidator.Validate(command).Returns([validationError]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + // The handler short-circuits on validation failure, so no authentication, lookup or persistence work is done. + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index 8100d620..781f2a39 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -47,6 +47,7 @@ public class GetUserPermissionsQueryHandlerTests public GetUserPermissionsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -79,7 +80,7 @@ public class GetUserPermissionsQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -96,7 +97,7 @@ public class GetUserPermissionsQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -108,7 +109,7 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -127,7 +128,7 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns((UserEntity?)null); // Act @@ -157,7 +158,7 @@ public class GetUserPermissionsQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(user); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index 15e3cde3..3d6dcddf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -44,6 +44,7 @@ public class GetUserRoleQueryHandlerTests public GetUserRoleQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockUserRepository = Substitute.For(); @@ -76,7 +77,7 @@ public class GetUserRoleQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -93,7 +94,7 @@ public class GetUserRoleQueryHandlerTests Assert.True(result.IsFailure); Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -105,7 +106,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -124,7 +125,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns((UserEntity?)null); // Act @@ -144,7 +145,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(user); // Act @@ -171,7 +172,7 @@ public class GetUserRoleQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); - _mockUserRepository.GetByIdAsync(query.UserId!.Value, Arg.Any()) + _mockUserRepository.GetByIdAsync(query.UserId!.Value, cancellationToken: Arg.Any()) .Returns(user); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs index a3ad3a9c..9b4c7a08 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -40,6 +40,7 @@ public class UpdateUserSettingsCommandHandlerTests public UpdateUserSettingsCommandHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs index 81ce23ea..a0a0df49 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs @@ -38,6 +38,7 @@ public class GetUserSettingsQueryHandlerTests public GetUserSettingsQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockCurrentUserService = Substitute.For(); _mockUserSettingsRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/PermissionDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/PermissionDtoTests.cs deleted file mode 100644 index 2c09dd77..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/PermissionDtoTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Authentication; -using Lumina.Contracts.Fixtures.Core.DTO.Authentication; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PermissionDtoTests -{ - private readonly PermissionDtoFixture _permissionDtoFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingPermission_ShouldPreserveValues() - { - // Arrange - PermissionDto expected = _permissionDtoFixture.Create(permissionName: AuthorizationPermission.CanViewUsers); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PermissionDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingPermission_ShouldSerializeEnumAsCamelCaseString() - { - // Arrange - PermissionDto sut = _permissionDtoFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"PermissionName\":\"canDeleteUsers\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - Guid id = Guid.NewGuid(); - PermissionDto first = _permissionDtoFixture.Create(id: id, permissionName: AuthorizationPermission.CanRegisterUsers); - PermissionDto second = _permissionDtoFixture.Create(id: id, permissionName: AuthorizationPermission.CanRegisterUsers); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/RoleDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/RoleDtoTests.cs deleted file mode 100644 index 1a442586..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/RoleDtoTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Authentication; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class RoleDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingRole_ShouldPreserveValues() - { - // Arrange - Guid id = Guid.NewGuid(); - RoleDto expected = new(id, "Admin"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RoleDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - Guid id = Guid.NewGuid(); - RoleDto first = new(id, "Admin"); - RoleDto second = new(id, "Admin"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs index 4b0fd356..c3f5de03 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs @@ -18,33 +18,6 @@ public class LibraryFilterDtoTests PropertyNameCaseInsensitive = true }; - [Fact] - public void LibraryFilterDto_WhenConstructed_ShouldRequireLibraryId() - { - // Act - LibraryFilterDto sut = new() { LibraryId = Guid.NewGuid(), SearchTerm = "test" }; - - // Assert - Assert.NotEqual(Guid.Empty, sut.LibraryId); - } - - [Fact] - public void RoundTrip_WhenSerializingWithLibraryIdAndSearchTerm_ShouldPreserveValues() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - LibraryFilterDto expected = new() { LibraryId = libraryId, SearchTerm = "fantasy" }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LibraryFilterDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected.LibraryId, actual.LibraryId); - Assert.Equal(expected.SearchTerm, actual.SearchTerm); - } - [Fact] public void RoundTrip_WhenDeserializingJsonWithoutLibraryId_ShouldThrowJsonException() { diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/GenreDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/GenreDtoTests.cs deleted file mode 100644 index bda11a0c..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/GenreDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.Common; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GenreDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingGenre_ShouldPreserveName() - { - // Arrange - GenreDto expected = new("Science Fiction"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GenreDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GenreDto first = new("Fantasy"); - GenreDto second = new("Fantasy"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/LanguageInfoDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/LanguageInfoDtoTests.cs deleted file mode 100644 index 431b12e4..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/LanguageInfoDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.Common; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LanguageInfoDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingFullyPopulatedLanguageInfo_ShouldPreserveValues() - { - // Arrange - LanguageInfoDto expected = new("en", "English", "English"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LanguageInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - LanguageInfoDto first = new("fr", "French", "Français"); - LanguageInfoDto second = new("fr", "French", "Français"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} 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 02e4fec9..bd30f269 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common.Pagination; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.DTO.Common.Pagination; @@ -12,11 +11,6 @@ namespace Lumina.Contracts.UnitTests.DTO.Common.Pagination; [ExcludeFromCodeCoverage] public class PaginationDataDtoTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - [Fact] public void CurrentPage_WhenNotSet_ShouldDefaultToOne() { @@ -98,20 +92,4 @@ public class PaginationDataDtoTests // Assert Assert.Equal(25, sut.PerPage); } - - [Fact] - public void RoundTrip_WhenSerializingValidPaginationData_ShouldPreserveValues() - { - // Arrange - PaginationDataDto expected = new() { CurrentPage = 3, PerPage = 50 }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PaginationDataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected.CurrentPage, actual.CurrentPage); - Assert.Equal(expected.PerPage, actual.PerPage); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/ReleaseInfoDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/ReleaseInfoDtoTests.cs deleted file mode 100644 index fee5323f..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/ReleaseInfoDtoTests.cs +++ /dev/null @@ -1,74 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.Common; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReleaseInfoDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingFullyPopulatedReleaseInfo_ShouldPreserveValues() - { - // Arrange - DateOnly originalReleaseDate = new(2005, 6, 15); - DateOnly reReleaseDate = new(2015, 9, 1); - ReleaseInfoDto expected = new( - originalReleaseDate, - 2005, - reReleaseDate, - 2015, - ReleaseCountry.US, - "Revised Edition" - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReleaseInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingEmptyReleaseInfo_ShouldPreserveNullValues() - { - // Arrange - ReleaseInfoDto expected = new(null, null, null, null, null, null); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReleaseInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - ReleaseInfoDto first = new(new DateOnly(2005, 6, 15), 2005, null, null, ReleaseCountry.US, null); - ReleaseInfoDto second = new(new DateOnly(2005, 6, 15), 2005, null, null, ReleaseCountry.US, null); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/TagDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/TagDtoTests.cs deleted file mode 100644 index c3302ff8..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/TagDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.Common; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class TagDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingTag_ShouldPreserveName() - { - // Arrange - TagDto expected = new("bestseller"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - TagDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - TagDto first = new("award-winning"); - TagDto second = new("award-winning"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/FileSystemManagement/FileSystemItemDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/FileSystemManagement/FileSystemItemDtoTests.cs deleted file mode 100644 index b0a67d22..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/FileSystemManagement/FileSystemItemDtoTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.FileSystemManagement; -using Lumina.Contracts.Fixtures.Core.DTO.FileSystemManagement; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.FileSystemManagement; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class FileSystemItemDtoTests -{ - private readonly FileSystemItemDtoFixture _fileSystemItemDtoFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidFileSystemItemDto() - { - // Act - FileSystemItemDto sut = _fileSystemItemDtoFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - Assert.False(string.IsNullOrWhiteSpace(sut.Name)); - } - - [Fact] - public void RoundTrip_WhenSerializingFileSystemItem_ShouldPreserveValues() - { - // Arrange - FileSystemItemDto expected = _fileSystemItemDtoFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - FileSystemItemDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - FileSystemItemDto first = _fileSystemItemDtoFixture.Create(); - FileSystemItemDto second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs deleted file mode 100644 index 39220186..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs +++ /dev/null @@ -1,54 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaContributors; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingContributor_ShouldPreserveValues() - { - // Arrange - MediaContributorDto expected = new( - new MediaContributorNameDto("John Smith", "Johnathan Smith"), - new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author) - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaContributorDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingContributorWithoutNameOrRole_ShouldPreserveNullValues() - { - // Arrange - MediaContributorDto expected = new(null, null); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaContributorDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.Name); - Assert.Null(actual.Role); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorNameDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorNameDtoTests.cs deleted file mode 100644 index c7321c39..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorNameDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaContributors; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaContributors; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorNameDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingName_ShouldPreserveValues() - { - // Arrange - MediaContributorNameDto expected = new("John Smith", "Johnathan Smith"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaContributorNameDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - MediaContributorNameDto first = new("John Smith", null); - MediaContributorNameDto second = new("John Smith", null); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs deleted file mode 100644 index 35423d71..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaContributors; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorRoleDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingRole_ShouldPreserveValues() - { - // Arrange - MediaContributorRoleDto expected = new("Author", MediaContributorRoleCategory.Author); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaContributorRoleDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - MediaContributorRoleDto first = new("Illustrator", null); - MediaContributorRoleDto second = new("Illustrator", null); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/Management/LibraryContentLocationDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/Management/LibraryContentLocationDtoTests.cs deleted file mode 100644 index 44e2e36e..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/Management/LibraryContentLocationDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.Management; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LibraryContentLocationDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingContentLocation_ShouldPreservePath() - { - // Arrange - LibraryContentLocationDto expected = new(@"C:\Media\Books"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LibraryContentLocationDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - LibraryContentLocationDto first = new(@"/media/books"); - LibraryContentLocationDto second = new(@"/media/books"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs deleted file mode 100644 index b6f29943..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs +++ /dev/null @@ -1,111 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class BookMetadataDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingFullyPopulatedMetadata_ShouldPreserveValues() - { - // Arrange - BookMetadataDto expected = new( - "Dune", - "Dune", - "A science fiction novel.", - new ReleaseInfoDto(new DateOnly(1965, 8, 1), 1965, null, null, ReleaseCountry.US, null), - [new GenreDto("Science Fiction")], - [new TagDto("classic")], - new LanguageInfoDto("en", "English", "English"), - null, - "Chilton Books", - 412, - BookFormat.Hardcover, - "First Edition", - 1, - new BookSeriesDto("Dune Chronicles"), - "B0006C7V9I", - "12345", - "68008446", - "ocm01234567", - "OL12345W", - "lccn123", - "abc123", - "1234567890", - "id12345", - [new IsbnDto("978-0-306-40615-7", IsbnFormat.Isbn13)], - [new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", MediaContributorRoleCategory.Author))], - [new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)], - "https://example.com/dune.jpg" - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookMetadataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingMetadata_ShouldSerializeFormatAsCamelCaseString() - { - // Arrange - BookMetadataDto sut = new( - "Dune", - null, - null, - null, - null, - null, - null, - null, - null, - null, - BookFormat.Paperback, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null - ); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Format\":\"paperback\"", json, StringComparison.Ordinal); - } -} 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 e09bd40c..81015d03 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 @@ -6,8 +6,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -18,36 +16,6 @@ namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.Book [ExcludeFromCodeCoverage] public class BookMetadataLookupDtoTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingLookupWithAllValues_ShouldPreserveValues() - { - // Arrange - Guid libraryId = Guid.NewGuid(); - BookMetadataLookupDto expected = new( - libraryId, - @"C:\Media\Books\dune.epub", - "978-0-306-40615-7", - "OL12345W", - "Dune", - "Frank Herbert", - "en" - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookMetadataLookupDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - [Fact] public void Constructor_WhenOmittingOptionalParameters_ShouldUseNullDefaults() { diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs index 477d40ea..c4807b7b 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs @@ -4,8 +4,6 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -18,74 +16,14 @@ public class BookRatingDtoTests { private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidBookRatingDto() - { - // Act - BookRatingDto sut = _bookRatingDtoFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.True(sut.Value.HasValue); - Assert.True(sut.MaxValue.HasValue); - } - [Fact] public void Create_WhenOmittingOptionalProperties_ShouldReturnNullSourceAndVoteCount() { // Act - BookRatingDto sut = _bookRatingDtoFixture.Create(includeOptionalProperties: false); + BookRatingDto sut = _bookRatingDtoFixture.Create(includeSource: false, includeVoteCount: false); // Assert Assert.Null(sut.Source); Assert.Null(sut.VoteCount); } - - [Fact] - public void RoundTrip_WhenSerializingRating_ShouldPreserveValues() - { - // Arrange - BookRatingDto expected = _bookRatingDtoFixture.Create(source: BookRatingSource.Goodreads); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookRatingDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingRating_ShouldSerializeSourceAsCamelCaseString() - { - // Arrange - BookRatingDto sut = _bookRatingDtoFixture.Create(source: BookRatingSource.OpenLibrary); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Source\":\"openLibrary\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - BookRatingDto first = _bookRatingDtoFixture.Create(value: 4, maxValue: 5, source: BookRatingSource.User, voteCount: 10); - BookRatingDto second = _bookRatingDtoFixture.Create(value: 4, maxValue: 5, source: BookRatingSource.User, voteCount: 10); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDtoTests.cs deleted file mode 100644 index 045d7b67..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class BookSeriesDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingSeries_ShouldPreserveTitle() - { - // Arrange - BookSeriesDto expected = new("The Wheel of Time"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookSeriesDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - BookSeriesDto first = new("Dune"); - BookSeriesDto second = new("Dune"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs index b47a13ec..53db6054 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs @@ -4,8 +4,6 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -18,23 +16,6 @@ public class IsbnDtoTests { private readonly IsbnDtoFixture _isbnDtoFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidIsbnDto() - { - // Act - IsbnDto sut = _isbnDtoFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Value)); - } - [Fact] public void Create_WhenFormatIsIsbn10_ShouldReturnIsbn10Value() { @@ -45,46 +26,4 @@ public class IsbnDtoTests Assert.Equal(IsbnFormat.Isbn10, sut.Format); Assert.Contains("-", sut.Value, StringComparison.Ordinal); } - - [Fact] - public void RoundTrip_WhenSerializingIsbn_ShouldPreserveValues() - { - // Arrange - IsbnDto expected = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - IsbnDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingIsbn_ShouldSerializeFormatAsCamelCaseString() - { - // Arrange - IsbnDto sut = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Format\":\"isbn13\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - IsbnDto first = _isbnDtoFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13); - IsbnDto second = _isbnDtoFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingDocumentDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingDocumentDtoTests.cs deleted file mode 100644 index 74dd0210..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingDocumentDtoTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingDocumentDtoTests -{ - private readonly ReadingDocumentDtoFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingDocumentDto() - { - // Act - ReadingDocumentDto sut = _fixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Title)); - Assert.NotEmpty(sut.Spine); - Assert.NotNull(sut.Resources); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingDocumentDto_ShouldPreserveValues() - { - // Arrange - ReadingDocumentDto expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingDocumentDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } -} 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 d8a8caad..bc6d8a34 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 @@ -3,7 +3,6 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Readin using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using System; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; @@ -15,22 +14,6 @@ namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.Book public class ReadingResourceDataDtoTests { private readonly ReadingResourceDataDtoFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingResourceDataDto() - { - // Act - ReadingResourceDataDto sut = _fixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEmpty(sut.Data); - Assert.False(string.IsNullOrWhiteSpace(sut.MimeType)); - } [Fact] public void Create_WhenProvidedData_ShouldPreserveIt() @@ -44,19 +27,4 @@ public class ReadingResourceDataDtoTests // Assert Assert.Equal(data, sut.Data); } - - [Fact] - public void RoundTrip_WhenSerializingReadingResourceDataDto_ShouldPreserveValues() - { - // Arrange - ReadingResourceDataDto expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingResourceDataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDtoTests.cs deleted file mode 100644 index 86b25f21..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingResourceInfoDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingResourceInfoDtoTests -{ - private readonly ReadingResourceInfoDtoFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingResourceInfoDto() - { - // Act - ReadingResourceInfoDto sut = _fixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.RelativeFilePath)); - Assert.False(string.IsNullOrWhiteSpace(sut.MimeType)); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingResourceInfoDto_ShouldPreserveValues() - { - // Arrange - ReadingResourceInfoDto expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingResourceInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDtoTests.cs deleted file mode 100644 index 49211192..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSectionDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingSectionDtoTests -{ - private readonly ReadingSectionDtoFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingSectionDto() - { - // Act - ReadingSectionDto sut = _fixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef)); - Assert.False(string.IsNullOrWhiteSpace(sut.ContentHtml)); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingSectionDto_ShouldPreserveValues() - { - // Arrange - ReadingSectionDto expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingSectionDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDtoTests.cs deleted file mode 100644 index 913ecc81..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingSpineItemDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingSpineItemDtoTests -{ - private readonly ReadingSpineItemDtoFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingSpineItemDto() - { - // Act - ReadingSpineItemDto sut = _fixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef)); - Assert.False(string.IsNullOrWhiteSpace(sut.RelativeSectionFilePath)); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingSpineItemDto_ShouldPreserveValues() - { - // Arrange - ReadingSpineItemDto expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingSpineItemDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDtoTests.cs deleted file mode 100644 index b052180f..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/Reading/ReadingTocEntryDtoTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingTocEntryDtoTests -{ - private readonly ReadingTocEntryDtoFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingTocEntryDto() - { - // Act - ReadingTocEntryDto sut = _fixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Label)); - Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef)); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingTocEntryDto_ShouldPreserveValues() - { - // Arrange - ReadingTocEntryDto expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingTocEntryDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoTests.cs deleted file mode 100644 index cc58a60c..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoTests.cs +++ /dev/null @@ -1,74 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class WrittenContentMetadataDtoTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingFullyPopulatedMetadata_ShouldPreserveValues() - { - // Arrange - WrittenContentMetadataDto expected = new( - "Dune", - "Dune", - "A science fiction novel.", - new ReleaseInfoDto(new DateOnly(1965, 8, 1), 1965, null, null, ReleaseCountry.US, null), - [new GenreDto("Science Fiction")], - [new TagDto("classic")], - new LanguageInfoDto("en", "English", "English"), - null, - "Chilton Books", - 412 - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - WrittenContentMetadataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingMetadataWithoutOptionalValues_ShouldPreserveNullValues() - { - // Arrange - WrittenContentMetadataDto expected = new( - "Title", - null, - null, - null, - null, - null, - null, - null, - null, - null - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - WrittenContentMetadataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/ChangePasswordRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/ChangePasswordRequestTests.cs deleted file mode 100644 index f3beab59..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/ChangePasswordRequestTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authentication; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ChangePasswordRequestTests -{ - private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidChangePasswordRequest() - { - // Act - ChangePasswordRequest sut = _changePasswordRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Username)); - Assert.False(string.IsNullOrWhiteSpace(sut.CurrentPassword)); - Assert.False(string.IsNullOrWhiteSpace(sut.NewPassword)); - Assert.Equal(sut.NewPassword, sut.NewPasswordConfirm); - } - - [Fact] - public void RoundTrip_WhenSerializingChangePasswordRequest_ShouldPreserveValues() - { - // Arrange - ChangePasswordRequest expected = _changePasswordRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ChangePasswordRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - ChangePasswordRequest sut = _changePasswordRequestFixture.Create(); - - // Act - (string? username, string? currentPassword, string? newPassword, string? newPasswordConfirm) = sut; - - // Assert - Assert.Equal(sut.Username, username); - Assert.Equal(sut.CurrentPassword, currentPassword); - Assert.Equal(sut.NewPassword, newPassword); - Assert.Equal(sut.NewPasswordConfirm, newPasswordConfirm); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/LoginRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/LoginRequestTests.cs deleted file mode 100644 index 2117e376..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/LoginRequestTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authentication; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LoginRequestTests -{ - private readonly LoginRequestFixture _loginRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidLoginRequest() - { - // Act - LoginRequest sut = _loginRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Username)); - Assert.False(string.IsNullOrWhiteSpace(sut.Password)); - } - - [Fact] - public void RoundTrip_WhenSerializingLoginRequest_ShouldPreserveValues() - { - // Arrange - LoginRequest expected = _loginRequestFixture.Create(totpCode: "123456"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LoginRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - LoginRequest first = new("user1", "pass1", null); - LoginRequest second = new("user1", "pass1", null); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - LoginRequest sut = _loginRequestFixture.Create(username: "user1", password: "pass1", totpCode: "123456"); - - // Act - (string? username, string? password, string? totpCode) = sut; - - // Assert - Assert.Equal(sut.Username, username); - Assert.Equal(sut.Password, password); - Assert.Equal(sut.TotpCode, totpCode); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RecoverPasswordRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RecoverPasswordRequestTests.cs deleted file mode 100644 index f0c3d8af..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RecoverPasswordRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authentication; -using Lumina.Contracts.Requests.Authentication; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class RecoverPasswordRequestTests -{ - private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidRecoverPasswordRequest() - { - // Act - RecoverPasswordRequest sut = _recoverPasswordRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Username)); - Assert.False(string.IsNullOrWhiteSpace(sut.TotpCode)); - } - - [Fact] - public void RoundTrip_WhenSerializingRecoverPasswordRequest_ShouldPreserveValues() - { - // Arrange - RecoverPasswordRequest expected = _recoverPasswordRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RecoverPasswordRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - RecoverPasswordRequest sut = _recoverPasswordRequestFixture.Create(username: "user1", totpCode: "123456"); - - // Act - (string? username, string? totpCode) = sut; - - // Assert - Assert.Equal(sut.Username, username); - Assert.Equal(sut.TotpCode, totpCode); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs index df2ed957..1e1c75a9 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.Requests.Authentication; @@ -13,26 +11,6 @@ namespace Lumina.Contracts.UnitTests.Requests.Authentication; [ExcludeFromCodeCoverage] public class RegistrationRequestTests { - private readonly RegistrationRequestFixture _registrationRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidRegistrationRequest() - { - // Act - RegistrationRequest sut = _registrationRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Username)); - Assert.False(string.IsNullOrWhiteSpace(sut.Password)); - Assert.Equal(sut.Password, sut.PasswordConfirm); - } - [Fact] public void Constructor_WhenOmittingUse2fa_ShouldDefaultToTrue() { @@ -42,35 +20,4 @@ public class RegistrationRequestTests // Assert Assert.True(sut.Use2fa); } - - [Fact] - public void RoundTrip_WhenSerializingRegistrationRequest_ShouldPreserveValues() - { - // Arrange - RegistrationRequest expected = _registrationRequestFixture.Create(use2fa: true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RegistrationRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - RegistrationRequest sut = _registrationRequestFixture.Create(username: "user1", password: "pass1", passwordConfirm: "pass1", use2fa: false); - - // Act - (string? username, string? password, string? passwordConfirm, bool use2fa) = sut; - - // Assert - Assert.Equal(sut.Username, username); - Assert.Equal(sut.Password, password); - Assert.Equal(sut.PasswordConfirm, passwordConfirm); - Assert.Equal(sut.Use2fa, use2fa); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs index 85e5b1bf..0d589fe8 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.Requests.Authorization; @@ -14,24 +11,6 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class AddRoleRequestTests { - private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidAddRoleRequest() - { - // Act - AddRoleRequest sut = _addRoleRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.RoleName)); - } - [Fact] public void Constructor_WhenPassingNullPermissions_ShouldReturnNullPermissions() { @@ -41,19 +20,4 @@ public class AddRoleRequestTests // Assert Assert.Null(sut.Permissions); } - - [Fact] - public void RoundTrip_WhenSerializingAddRoleRequest_ShouldPreserveValues() - { - // Arrange - AddRoleRequest expected = _addRoleRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - AddRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs index 26120a57..6aa9a43d 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.Requests.Authorization; @@ -13,24 +11,6 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class DeleteRoleRequestTests { - private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidDeleteRoleRequest() - { - // Act - DeleteRoleRequest sut = _deleteRoleRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.True(sut.RoleId.HasValue); - } - [Fact] public void Constructor_WhenPassingNullRoleId_ShouldReturnNullRoleId() { @@ -40,19 +20,4 @@ public class DeleteRoleRequestTests // Assert Assert.Null(sut.RoleId); } - - [Fact] - public void RoundTrip_WhenSerializingDeleteRoleRequest_ShouldPreserveValues() - { - // Arrange - DeleteRoleRequest expected = _deleteRoleRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - DeleteRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs index 45d11c62..b8c04302 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.Requests.Authorization; @@ -13,24 +11,6 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class GetAuthorizationRequestTests { - private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetAuthorizationRequest() - { - // Act - GetAuthorizationRequest sut = _getAuthorizationRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.True(sut.UserId.HasValue); - } - [Fact] public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() { @@ -40,19 +20,4 @@ public class GetAuthorizationRequestTests // Assert Assert.Null(sut.UserId); } - - [Fact] - public void RoundTrip_WhenSerializingGetAuthorizationRequest_ShouldPreserveValues() - { - // Arrange - GetAuthorizationRequest expected = _getAuthorizationRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetAuthorizationRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetRolePermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetRolePermissionsRequestTests.cs deleted file mode 100644 index 9c88fdf1..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetRolePermissionsRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; -using Lumina.Contracts.Requests.Authorization; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetRolePermissionsRequestTests -{ - private readonly GetRolePermissionsRequestFixture _getRolePermissionsRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetRolePermissionsRequest() - { - // Act - GetRolePermissionsRequest sut = _getRolePermissionsRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.RoleId); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetRolePermissionsRequest first = _getRolePermissionsRequestFixture.Create(); - GetRolePermissionsRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingGetRolePermissionsRequest_ShouldPreserveValues() - { - // Arrange - GetRolePermissionsRequest expected = _getRolePermissionsRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetRolePermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs index 008c13de..f8c30af2 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.Requests.Authorization; @@ -13,24 +11,6 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class GetUserPermissionsRequestTests { - private readonly GetUserPermissionsRequestFixture _getUserPermissionsRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetUserPermissionsRequest() - { - // Act - GetUserPermissionsRequest sut = _getUserPermissionsRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.True(sut.UserId.HasValue); - } - [Fact] public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() { @@ -40,19 +20,4 @@ public class GetUserPermissionsRequestTests // Assert Assert.Null(sut.UserId); } - - [Fact] - public void RoundTrip_WhenSerializingGetUserPermissionsRequest_ShouldPreserveValues() - { - // Arrange - GetUserPermissionsRequest expected = _getUserPermissionsRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetUserPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs index a37ba302..29dafa4b 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; #endregion namespace Lumina.Contracts.UnitTests.Requests.Authorization; @@ -13,24 +11,6 @@ namespace Lumina.Contracts.UnitTests.Requests.Authorization; [ExcludeFromCodeCoverage] public class GetUserRoleRequestTests { - private readonly GetUserRoleRequestFixture _getUserRoleRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetUserRoleRequest() - { - // Act - GetUserRoleRequest sut = _getUserRoleRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.True(sut.UserId.HasValue); - } - [Fact] public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() { @@ -40,19 +20,4 @@ public class GetUserRoleRequestTests // Assert Assert.Null(sut.UserId); } - - [Fact] - public void RoundTrip_WhenSerializingGetUserRoleRequest_ShouldPreserveValues() - { - // Arrange - GetUserRoleRequest expected = _getUserRoleRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetUserRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateRoleRequestTests.cs deleted file mode 100644 index dceaa6ed..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateRoleRequestTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; -using Lumina.Contracts.Requests.Authorization; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UpdateRoleRequestTests -{ - private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUpdateRoleRequest_ShouldPreserveValues() - { - // Arrange - UpdateRoleRequest expected = _updateRoleRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingUpdateRoleRequestWithNullPermissions_ShouldPreserveNull() - { - // Arrange - UpdateRoleRequest expected = _updateRoleRequestFixture.Create() with { Permissions = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.Permissions); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateUserRoleAndPermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateUserRoleAndPermissionsRequestTests.cs deleted file mode 100644 index 15d0d8f9..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateUserRoleAndPermissionsRequestTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Authorization; -using Lumina.Contracts.Requests.Authorization; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UpdateUserRoleAndPermissionsRequestTests -{ - private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUpdateUserRoleAndPermissionsRequest_ShouldPreserveValues() - { - // Arrange - UpdateUserRoleAndPermissionsRequest expected = _updateUserRoleAndPermissionsRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateUserRoleAndPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingWithOptionalValuesOmitted_ShouldPreserveNulls() - { - // Arrange - UpdateUserRoleAndPermissionsRequest expected = _updateUserRoleAndPermissionsRequestFixture.Create() with { RoleId = null, Permissions = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateUserRoleAndPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.RoleId); - Assert.Null(actual.Permissions); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Directories/GetDirectoriesRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Directories/GetDirectoriesRequestTests.cs deleted file mode 100644 index 5e2c5cf8..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Directories/GetDirectoriesRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Directories; -using Lumina.Contracts.Requests.FileSystemManagement.Directories; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Directories; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetDirectoriesRequestTests -{ - private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetDirectoriesRequest() - { - // Act - GetDirectoriesRequest sut = _getDirectoriesRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetDirectoriesRequest_ShouldPreserveValues() - { - // Arrange - GetDirectoriesRequest expected = _getDirectoriesRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetDirectoriesRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - GetDirectoriesRequest sut = _getDirectoriesRequestFixture.Create(path: @"C:\Media", includeHiddenElements: true); - - // Act - (string? path, bool includeHiddenElements) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetFilesRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetFilesRequestTests.cs deleted file mode 100644 index 1c47e9d6..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetFilesRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; -using Lumina.Contracts.Requests.FileSystemManagement.Files; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Files; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetFilesRequestTests -{ - private readonly GetFilesRequestFixture _getFilesRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetFilesRequest() - { - // Act - GetFilesRequest sut = _getFilesRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetFilesRequest_ShouldPreserveValues() - { - // Arrange - GetFilesRequest expected = _getFilesRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetFilesRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - GetFilesRequest sut = _getFilesRequestFixture.Create(path: @"C:\Media", includeHiddenElements: true); - - // Act - (string? path, bool includeHiddenElements) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetTreeFilesRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetTreeFilesRequestTests.cs deleted file mode 100644 index cf41d6c8..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetTreeFilesRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; -using Lumina.Contracts.Requests.FileSystemManagement.Files; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Files; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetTreeFilesRequestTests -{ - private readonly GetTreeFilesRequestFixture _getTreeFilesRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetTreeFilesRequest() - { - // Act - GetTreeFilesRequest sut = _getTreeFilesRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetTreeFilesRequest_ShouldPreserveValues() - { - // Arrange - GetTreeFilesRequest expected = _getTreeFilesRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetTreeFilesRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - GetTreeFilesRequest sut = _getTreeFilesRequestFixture.Create(path: @"C:\Media", includeHiddenElements: false); - - // Act - (string? path, bool includeHiddenElements) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CheckPathExistsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CheckPathExistsRequestTests.cs deleted file mode 100644 index d452f298..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CheckPathExistsRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class CheckPathExistsRequestTests -{ - private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidCheckPathExistsRequest() - { - // Act - CheckPathExistsRequest sut = _checkPathExistsRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingCheckPathExistsRequest_ShouldPreserveValues() - { - // Arrange - CheckPathExistsRequest expected = _checkPathExistsRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - CheckPathExistsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - CheckPathExistsRequest sut = _checkPathExistsRequestFixture.Create(path: @"C:\Media\Books", includeHiddenElements: true); - - // Act - (string? path, bool includeHiddenElements) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CombinePathRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CombinePathRequestTests.cs deleted file mode 100644 index 9f610065..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CombinePathRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class CombinePathRequestTests -{ - private readonly CombinePathRequestFixture _combinePathRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidCombinePathRequest() - { - // Act - CombinePathRequest sut = _combinePathRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.OriginalPath)); - Assert.False(string.IsNullOrWhiteSpace(sut.NewPath)); - } - - [Fact] - public void RoundTrip_WhenSerializingCombinePathRequest_ShouldPreserveValues() - { - // Arrange - CombinePathRequest expected = _combinePathRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - CombinePathRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - CombinePathRequest sut = _combinePathRequestFixture.Create(originalPath: @"C:\Media", newPath: "books"); - - // Act - (string? originalPath, string? newPath) = sut; - - // Assert - Assert.Equal(sut.OriginalPath, originalPath); - Assert.Equal(sut.NewPath, newPath); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathParentRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathParentRequestTests.cs deleted file mode 100644 index c76597db..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathParentRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetPathParentRequestTests -{ - private readonly GetPathParentRequestFixture _getPathParentRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetPathParentRequest() - { - // Act - GetPathParentRequest sut = _getPathParentRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetPathParentRequest_ShouldPreserveValues() - { - // Arrange - GetPathParentRequest expected = _getPathParentRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetPathParentRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetPathParentRequest first = _getPathParentRequestFixture.Create(path: @"C:\Media\Books"); - GetPathParentRequest second = _getPathParentRequestFixture.Create(path: @"C:\Media\Books"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathRootRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathRootRequestTests.cs deleted file mode 100644 index 7fe7263e..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathRootRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetPathRootRequestTests -{ - private readonly GetPathRootRequestFixture _getPathRootRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetPathRootRequest() - { - // Act - GetPathRootRequest sut = _getPathRootRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetPathRootRequest_ShouldPreserveValues() - { - // Arrange - GetPathRootRequest expected = _getPathRootRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetPathRootRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetPathRootRequest first = _getPathRootRequestFixture.Create(path: @"C:\Media\Books"); - GetPathRootRequest second = _getPathRootRequestFixture.Create(path: @"C:\Media\Books"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/SplitPathRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/SplitPathRequestTests.cs deleted file mode 100644 index 7383f6a3..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/SplitPathRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class SplitPathRequestTests -{ - private readonly SplitPathRequestFixture _splitPathRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidSplitPathRequest() - { - // Act - SplitPathRequest sut = _splitPathRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingSplitPathRequest_ShouldPreserveValues() - { - // Arrange - SplitPathRequest expected = _splitPathRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - SplitPathRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - SplitPathRequest first = _splitPathRequestFixture.Create(path: @"C:\Media\Books"); - SplitPathRequest second = _splitPathRequestFixture.Create(path: @"C:\Media\Books"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/ValidatePathRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/ValidatePathRequestTests.cs deleted file mode 100644 index 9c38e380..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/ValidatePathRequestTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; -using Lumina.Contracts.Requests.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ValidatePathRequestTests -{ - private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidValidatePathRequest() - { - // Act - ValidatePathRequest sut = _validatePathRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingValidatePathRequest_ShouldPreserveValues() - { - // Arrange - ValidatePathRequest expected = _validatePathRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ValidatePathRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - ValidatePathRequest first = _validatePathRequestFixture.Create(path: @"C:\Media\Books"); - ValidatePathRequest second = _validatePathRequestFixture.Create(path: @"C:\Media\Books"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestTests.cs deleted file mode 100644 index accf4387..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Thumbnails; -using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Thumbnails; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetThumbnailRequestTests -{ - private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetThumbnailRequest() - { - // Act - GetThumbnailRequest sut = _getThumbnailRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - Assert.InRange(sut.Quality, 1, 100); - } - - [Fact] - public void RoundTrip_WhenSerializingGetThumbnailRequest_ShouldPreserveValues() - { - // Arrange - GetThumbnailRequest expected = _getThumbnailRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetThumbnailRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - GetThumbnailRequest sut = _getThumbnailRequestFixture.Create(path: @"C:\Media\cover.jpg", quality: 80); - - // Act - (string? path, int quality) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.Quality, quality); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs deleted file mode 100644 index 11e0ea34..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class AddLibraryRequestTests -{ - private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingAddLibraryRequest_ShouldPreserveValues() - { - // Arrange - AddLibraryRequest expected = _addLibraryRequestFixture.Create( - title: "Books", - libraryType: "Book", - contentLocations: [@"C:\Media\Books"], - coverImage: null, - isEnabled: true, - isLocked: false, - canDownloadMetadataFromWeb: true, - shouldSaveMetadataInMediaDirectories: false, - shouldSkipUnchangedDirectoriesDuringScan: true - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - AddLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - AddLibraryRequest sut = _addLibraryRequestFixture.Create( - title: "Books", - libraryType: "Book", - contentLocations: [@"C:\Media\Books"], - coverImage: null, - isEnabled: true, - isLocked: false, - canDownloadMetadataFromWeb: true, - shouldSaveMetadataInMediaDirectories: false, - shouldSkipUnchangedDirectoriesDuringScan: true - ); - - // Act - (string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; - - // Assert - Assert.Equal(sut.Title, title); - Assert.Equal(sut.LibraryType, libraryType); - Assert.Equal(sut.ContentLocations, contentLocations); - Assert.Equal(sut.CoverImage, coverImage); - Assert.Equal(sut.IsEnabled, isEnabled); - Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); - Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); - Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/CancelLibraryScanRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/CancelLibraryScanRequestTests.cs deleted file mode 100644 index 94a32d68..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/CancelLibraryScanRequestTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class CancelLibraryScanRequestTests -{ - private readonly CancelLibraryScanRequestFixture _cancelLibraryScanRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidCancelLibraryScanRequest() - { - // Act - CancelLibraryScanRequest sut = _cancelLibraryScanRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.NotEqual(Guid.Empty, sut.ScanId); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - CancelLibraryScanRequest first = _cancelLibraryScanRequestFixture.Create(); - CancelLibraryScanRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingCancelLibraryScanRequest_ShouldPreserveValues() - { - // Arrange - CancelLibraryScanRequest expected = _cancelLibraryScanRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - CancelLibraryScanRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/DeleteLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/DeleteLibraryRequestTests.cs deleted file mode 100644 index 031f4f72..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/DeleteLibraryRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class DeleteLibraryRequestTests -{ - private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidDeleteLibraryRequest() - { - // Act - DeleteLibraryRequest sut = _deleteLibraryRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.Id); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - DeleteLibraryRequest first = _deleteLibraryRequestFixture.Create(); - DeleteLibraryRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingDeleteLibraryRequest_ShouldPreserveValues() - { - // Arrange - DeleteLibraryRequest expected = _deleteLibraryRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - DeleteLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryRequestTests.cs deleted file mode 100644 index f4736e22..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetLibraryRequestTests -{ - private readonly GetLibraryRequestFixture _getLibraryRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetLibraryRequest() - { - // Act - GetLibraryRequest sut = _getLibraryRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.Id); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetLibraryRequest first = _getLibraryRequestFixture.Create(); - GetLibraryRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingGetLibraryRequest_ShouldPreserveValues() - { - // Arrange - GetLibraryRequest expected = _getLibraryRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestTests.cs deleted file mode 100644 index e8af2d79..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetLibraryScanProgressRequestTests -{ - private readonly GetLibraryScanProgressRequestFixture _getLibraryScanProgressRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetLibraryScanProgressRequest() - { - // Act - GetLibraryScanProgressRequest sut = _getLibraryScanProgressRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.NotEqual(Guid.Empty, sut.ScanId); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetLibraryScanProgressRequest first = _getLibraryScanProgressRequestFixture.Create(); - GetLibraryScanProgressRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingGetLibraryScanProgressRequest_ShouldPreserveValues() - { - // Arrange - GetLibraryScanProgressRequest expected = _getLibraryScanProgressRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetLibraryScanProgressRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/ScanLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/ScanLibraryRequestTests.cs deleted file mode 100644 index 36ab6d93..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/ScanLibraryRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ScanLibraryRequestTests -{ - private readonly ScanLibraryRequestFixture _scanLibraryRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidScanLibraryRequest() - { - // Act - ScanLibraryRequest sut = _scanLibraryRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.Id); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - ScanLibraryRequest first = _scanLibraryRequestFixture.Create(); - ScanLibraryRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingScanLibraryRequest_ShouldPreserveValues() - { - // Arrange - ScanLibraryRequest expected = _scanLibraryRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ScanLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs deleted file mode 100644 index f384abee..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; -using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UpdateLibraryRequestTests -{ - private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUpdateLibraryRequest_ShouldPreserveValues() - { - // Arrange - Guid id = Guid.NewGuid(); - Guid userId = Guid.NewGuid(); - UpdateLibraryRequest expected = _updateLibraryRequestFixture.Create( - id: id, - userId: userId, - title: "Books", - libraryType: "Book", - contentLocations: [@"C:\Media\Books"], - coverImage: null, - isEnabled: true, - isLocked: false, - canDownloadMetadataFromWeb: true, - shouldSaveMetadataInMediaDirectories: false, - shouldSkipUnchangedDirectoriesDuringScan: true - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - Guid id = Guid.NewGuid(); - Guid userId = Guid.NewGuid(); - UpdateLibraryRequest sut = _updateLibraryRequestFixture.Create( - id: id, - userId: userId, - title: "Books", - libraryType: "Book", - contentLocations: [@"C:\Media\Books"], - coverImage: null, - isEnabled: true, - isLocked: false, - canDownloadMetadataFromWeb: true, - shouldSaveMetadataInMediaDirectories: false, - shouldSkipUnchangedDirectoriesDuringScan: true - ); - - // Act - (Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; - - // Assert - Assert.Equal(sut.Id, sutId); - Assert.Equal(sut.UserId, sutUserId); - Assert.Equal(sut.Title, title); - Assert.Equal(sut.LibraryType, libraryType); - Assert.Equal(sut.ContentLocations, contentLocations); - Assert.Equal(sut.CoverImage, coverImage); - Assert.Equal(sut.IsEnabled, isEnabled); - Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); - Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); - Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs deleted file mode 100644 index 80ba7f10..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class AddBookRequestTests -{ - private readonly AddBookRequestFixture _addBookRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidAddBookRequest() - { - // Act - AddBookRequest sut = _addBookRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - Assert.NotNull(sut.Metadata); - Assert.NotNull(sut.ISBNs); - Assert.NotEmpty(sut.ISBNs); - Assert.NotNull(sut.Contributors); - Assert.NotEmpty(sut.Contributors); - Assert.NotNull(sut.Ratings); - Assert.NotEmpty(sut.Ratings); - } - - [Fact] - public void RoundTrip_WhenSerializingAddBookRequest_ShouldPreserveValues() - { - // Arrange - AddBookRequest expected = _addBookRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - AddBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingAddBookRequest_ShouldSerializeFormatAsCamelCaseString() - { - // Arrange - AddBookRequest sut = _addBookRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Format\":\"", json, StringComparison.Ordinal); - Assert.DoesNotContain("\"Format\":\"0\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - AddBookRequest sut = _addBookRequestFixture.Create(); - - // Act - (Guid libraryId, string path, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List? isbns, List? contributors, List? ratings) = sut; - - // Assert - Assert.Equal(sut.LibraryId, libraryId); - Assert.Equal(sut.Path, path); - Assert.Equal(sut.Metadata, metadata); - Assert.Equal(sut.Format, format); - Assert.Equal(sut.Edition, edition); - Assert.Equal(sut.VolumeNumber, volumeNumber); - Assert.Equal(sut.Series, series); - Assert.Equal(sut.ASIN, asin); - Assert.Equal(sut.GoodreadsId, goodreadsId); - Assert.Equal(sut.LCCN, lccn); - Assert.Equal(sut.OCLCNumber, oclcNumber); - Assert.Equal(sut.OpenLibraryId, openLibraryId); - Assert.Equal(sut.LibraryThingId, libraryThingId); - Assert.Equal(sut.GoogleBooksId, googleBooksId); - Assert.Equal(sut.BarnesAndNobleId, barnesAndNobleId); - Assert.Equal(sut.AppleBooksId, appleBooksId); - Assert.Equal(sut.ISBNs, isbns); - Assert.Equal(sut.Contributors, contributors); - Assert.Equal(sut.Ratings, ratings); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - AddBookRequest first = _addBookRequestFixture.Create(); - AddBookRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestTests.cs deleted file mode 100644 index 4d392d51..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetBookRequestTests -{ - private readonly GetBookRequestFixture _getBookRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetBookRequest() - { - // Act - GetBookRequest sut = _getBookRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Id)); - } - - [Fact] - public void Constructor_WhenPassingNullId_ShouldReturnNullId() - { - // Act - GetBookRequest sut = new(Id: null); - - // Assert - Assert.Null(sut.Id); - } - - [Fact] - public void RoundTrip_WhenSerializingGetBookRequest_ShouldPreserveValues() - { - // Arrange - GetBookRequest expected = _getBookRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs deleted file mode 100644 index ad60760c..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetBooksLiteRequestTests -{ - private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetBooksLiteRequest() - { - // Act - GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.True(sut.CurrentPage.HasValue); - Assert.True(sut.PerPage.HasValue); - } - - [Fact] - public void RoundTrip_WhenSerializingGetBooksLiteRequest_ShouldPreserveValues() - { - // Arrange - GetBooksLiteRequest expected = _getBooksLiteRequestFixture.Create(sortOrder: SortOrder.Descending); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetBooksLiteRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingGetBooksLiteRequest_ShouldSerializeSortOrderAsCamelCaseString() - { - // Arrange - GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(sortOrder: SortOrder.Ascending); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"SortOrder\":\"ascending\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(); - - // Act - (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut; - - // Assert - Assert.Equal(sut.LibraryId, libraryId); - Assert.Equal(sut.CurrentPage, currentPage); - Assert.Equal(sut.PerPage, perPage); - Assert.Equal(sut.SearchTerm, searchTerm); - Assert.Equal(sut.FilterAlphaKey, filterAlphaKey); - Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); - Assert.Equal(sut.SortBy, sortBy); - Assert.Equal(sut.SortOrder, sortOrder); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs deleted file mode 100644 index 1b573070..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetBooksRequestTests -{ - private readonly GetBooksRequestFixture _getBooksRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetBooksRequest() - { - // Act - GetBooksRequest sut = _getBooksRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.True(sut.CurrentPage.HasValue); - Assert.True(sut.PerPage.HasValue); - } - - [Fact] - public void RoundTrip_WhenSerializingGetBooksRequest_ShouldPreserveValues() - { - // Arrange - GetBooksRequest expected = _getBooksRequestFixture.Create(sortOrder: SortOrder.Ascending); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetBooksRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingGetBooksRequest_ShouldSerializeSortOrderAsCamelCaseString() - { - // Arrange - GetBooksRequest sut = _getBooksRequestFixture.Create(sortOrder: SortOrder.Descending); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"SortOrder\":\"descending\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - GetBooksRequest sut = _getBooksRequestFixture.Create(); - - // Act - (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? sortBy, SortOrder? sortOrder) = sut; - - // Assert - Assert.Equal(sut.LibraryId, libraryId); - Assert.Equal(sut.CurrentPage, currentPage); - Assert.Equal(sut.PerPage, perPage); - Assert.Equal(sut.SearchTerm, searchTerm); - Assert.Equal(sut.SortBy, sortBy); - Assert.Equal(sut.SortOrder, sortOrder); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestTests.cs deleted file mode 100644 index d2606809..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingAvailabilityRequestTests -{ - private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetReadingAvailabilityRequest() - { - // Act - GetReadingAvailabilityRequest sut = _getReadingAvailabilityRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.BookId); - } - - [Fact] - public void RoundTrip_WhenSerializingGetReadingAvailabilityRequest_ShouldPreserveValues() - { - // Arrange - GetReadingAvailabilityRequest expected = _getReadingAvailabilityRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetReadingAvailabilityRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestTests.cs deleted file mode 100644 index 79b914fe..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingManifestRequestTests -{ - private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetReadingManifestRequest() - { - // Act - GetReadingManifestRequest sut = _getReadingManifestRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.BookId); - } - - [Fact] - public void RoundTrip_WhenSerializingGetReadingManifestRequest_ShouldPreserveValues() - { - // Arrange - GetReadingManifestRequest expected = _getReadingManifestRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetReadingManifestRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestTests.cs deleted file mode 100644 index 3c07d665..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingResourceRequestTests -{ - private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetReadingResourceRequest() - { - // Act - GetReadingResourceRequest sut = _getReadingResourceRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.BookId); - Assert.False(string.IsNullOrWhiteSpace(sut.ResourceKey)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetReadingResourceRequest_ShouldPreserveValues() - { - // Arrange - GetReadingResourceRequest expected = _getReadingResourceRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetReadingResourceRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestTests.cs deleted file mode 100644 index 03a301a4..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetReadingSectionRequestTests -{ - private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetReadingSectionRequest() - { - // Act - GetReadingSectionRequest sut = _getReadingSectionRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.BookId); - Assert.False(string.IsNullOrWhiteSpace(sut.LocationRef)); - } - - [Fact] - public void RoundTrip_WhenSerializingGetReadingSectionRequest_ShouldPreserveValues() - { - // Arrange - GetReadingSectionRequest expected = _getReadingSectionRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetReadingSectionRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs deleted file mode 100644 index be7ca823..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestTests.cs +++ /dev/null @@ -1,121 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UpdateBookRequestTests -{ - private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidUpdateBookRequest() - { - // Act - UpdateBookRequest sut = _updateBookRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Id)); - Assert.NotNull(sut.Metadata); - Assert.NotNull(sut.ISBNs); - Assert.NotEmpty(sut.ISBNs); - Assert.NotNull(sut.Contributors); - Assert.NotEmpty(sut.Contributors); - Assert.NotNull(sut.Ratings); - Assert.NotEmpty(sut.Ratings); - } - - [Fact] - public void RoundTrip_WhenSerializingUpdateBookRequest_ShouldPreserveValues() - { - // Arrange - UpdateBookRequest expected = _updateBookRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingUpdateBookRequest_ShouldSerializeFormatAsCamelCaseString() - { - // Arrange - UpdateBookRequest sut = _updateBookRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Format\":\"", json, StringComparison.Ordinal); - Assert.DoesNotContain("\"Format\":\"0\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - UpdateBookRequest sut = _updateBookRequestFixture.Create(); - - // Act - (string? id, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List? isbns, List? contributors, List? ratings) = sut; - - // Assert - Assert.Equal(sut.Id, id); - Assert.Equal(sut.Metadata, metadata); - Assert.Equal(sut.Format, format); - Assert.Equal(sut.Edition, edition); - Assert.Equal(sut.VolumeNumber, volumeNumber); - Assert.Equal(sut.Series, series); - Assert.Equal(sut.ASIN, asin); - Assert.Equal(sut.GoodreadsId, goodreadsId); - Assert.Equal(sut.LCCN, lccn); - Assert.Equal(sut.OCLCNumber, oclcNumber); - Assert.Equal(sut.OpenLibraryId, openLibraryId); - Assert.Equal(sut.LibraryThingId, libraryThingId); - Assert.Equal(sut.GoogleBooksId, googleBooksId); - Assert.Equal(sut.BarnesAndNobleId, barnesAndNobleId); - Assert.Equal(sut.AppleBooksId, appleBooksId); - Assert.Equal(sut.ISBNs, isbns); - Assert.Equal(sut.Contributors, contributors); - Assert.Equal(sut.Ratings, ratings); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - UpdateBookRequest first = _updateBookRequestFixture.Create(); - UpdateBookRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryBookReadersRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryBookReadersRequestTests.cs deleted file mode 100644 index bb060516..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryBookReadersRequestTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetLibraryBookReadersRequestTests -{ - private readonly GetLibraryBookReadersRequestFixture _getLibraryBookReadersRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetLibraryBookReadersRequest() - { - // Act - GetLibraryBookReadersRequest sut = _getLibraryBookReadersRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - } - - [Fact] - public void RoundTrip_WhenSerializingGetLibraryBookReadersRequest_ShouldPreserveValues() - { - // Arrange - GetLibraryBookReadersRequest expected = _getLibraryBookReadersRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetLibraryBookReadersRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryMetadataProvidersRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryMetadataProvidersRequestTests.cs deleted file mode 100644 index 1aaeb820..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryMetadataProvidersRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetLibraryMetadataProvidersRequestTests -{ - private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetLibraryMetadataProvidersRequest() - { - // Act - GetLibraryMetadataProvidersRequest sut = _getLibraryMetadataProvidersRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetLibraryMetadataProvidersRequest first = _getLibraryMetadataProvidersRequestFixture.Create(); - GetLibraryMetadataProvidersRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingGetLibraryMetadataProvidersRequest_ShouldPreserveValues() - { - // Arrange - GetLibraryMetadataProvidersRequest expected = _getLibraryMetadataProvidersRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetLibraryMetadataProvidersRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetPluginSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetPluginSettingsRequestTests.cs deleted file mode 100644 index b05180ec..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetPluginSettingsRequestTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class GetPluginSettingsRequestTests -{ - private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidGetPluginSettingsRequest() - { - // Act - GetPluginSettingsRequest sut = _getPluginSettingsRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.PluginId); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - GetPluginSettingsRequest first = _getPluginSettingsRequestFixture.Create(); - GetPluginSettingsRequest second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void RoundTrip_WhenSerializingGetPluginSettingsRequest_ShouldPreserveValues() - { - // Arrange - GetPluginSettingsRequest expected = _getPluginSettingsRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - GetPluginSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/ReorderLibraryMetadataProvidersRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/ReorderLibraryMetadataProvidersRequestTests.cs deleted file mode 100644 index c2829386..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/ReorderLibraryMetadataProvidersRequestTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Collections.Generic; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReorderLibraryMetadataProvidersRequestTests -{ - private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReorderLibraryMetadataProvidersRequest() - { - // Act - ReorderLibraryMetadataProvidersRequest sut = _reorderLibraryMetadataProvidersRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.True(sut.PluginIds.Count > 0); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - ReorderLibraryMetadataProvidersRequest sut = _reorderLibraryMetadataProvidersRequestFixture.Create(); - - // Act - (Guid sutLibraryId, IReadOnlyList sutPluginIds) = sut; - - // Assert - Assert.Equal(sut.LibraryId, sutLibraryId); - Assert.Equal(sut.PluginIds, sutPluginIds); - } - - [Fact] - public void RoundTrip_WhenSerializingReorderLibraryMetadataProvidersRequest_ShouldPreserveValues() - { - // Arrange - ReorderLibraryMetadataProvidersRequest expected = _reorderLibraryMetadataProvidersRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReorderLibraryMetadataProvidersRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryBookReaderEnabledRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryBookReaderEnabledRequestTests.cs deleted file mode 100644 index ec75d99c..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryBookReaderEnabledRequestTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryBookReaderEnabledRequestTests -{ - private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidSetLibraryBookReaderEnabledRequest() - { - // Act - SetLibraryBookReaderEnabledRequest sut = _setLibraryBookReaderEnabledRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.NotEqual(Guid.Empty, sut.PluginId); - } - - [Fact] - public void RoundTrip_WhenSerializingSetLibraryBookReaderEnabledRequest_ShouldPreserveValues() - { - // Arrange - SetLibraryBookReaderEnabledRequest expected = _setLibraryBookReaderEnabledRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - SetLibraryBookReaderEnabledRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestTests.cs deleted file mode 100644 index 8d813755..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class SetLibraryMetadataProviderEnabledRequestTests -{ - private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidSetLibraryMetadataProviderEnabledRequest() - { - // Act - SetLibraryMetadataProviderEnabledRequest sut = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(Guid.Empty, sut.LibraryId); - Assert.NotEqual(Guid.Empty, sut.PluginId); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest sut = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - - // Act - (Guid sutLibraryId, Guid sutPluginId, bool isEnabled) = sut; - - // Assert - Assert.Equal(sut.LibraryId, sutLibraryId); - Assert.Equal(sut.PluginId, sutPluginId); - Assert.Equal(sut.IsEnabled, isEnabled); - } - - [Fact] - public void RoundTrip_WhenSerializingSetLibraryMetadataProviderEnabledRequest_ShouldPreserveValues() - { - // Arrange - SetLibraryMetadataProviderEnabledRequest expected = _setLibraryMetadataProviderEnabledRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - SetLibraryMetadataProviderEnabledRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/UpdatePluginSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/UpdatePluginSettingsRequestTests.cs deleted file mode 100644 index a4c2b14b..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/UpdatePluginSettingsRequestTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.Plugins; -using Lumina.Contracts.Requests.Plugins; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UpdatePluginSettingsRequestTests -{ - private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUpdatePluginSettingsRequest_ShouldPreserveValues() - { - // Arrange - UpdatePluginSettingsRequest expected = _updatePluginSettingsRequestFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdatePluginSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingUpdatePluginSettingsRequestWithNullSettings_ShouldPreserveNull() - { - // Arrange - UpdatePluginSettingsRequest expected = _updatePluginSettingsRequestFixture.Create() with { Settings = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdatePluginSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.Settings); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs deleted file mode 100644 index e286e012..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; -using Lumina.Contracts.Requests.UsersManagement.Settings; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Requests.UsersManagement.Settings; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UpdateUserSettingsRequestTests -{ - private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues() - { - // Arrange - UpdateUserSettingsRequest expected = _updateUserSettingsRequestFixture.Create( - isPaginationEnabled: true, - itemsPerPage: 50, - shouldIgnoreThePrefixForAlphaPicker: true, - isThemeCachingEnabled: true, - shouldAggregateMetadataWhenMissing: false - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UpdateUserSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - UpdateUserSettingsRequest sut = _updateUserSettingsRequestFixture.Create( - isPaginationEnabled: false, - itemsPerPage: 25, - shouldIgnoreThePrefixForAlphaPicker: false, - isThemeCachingEnabled: false, - shouldAggregateMetadataWhenMissing: false, - shouldRenderPdfAsImages: true, - shouldPreserveBookStyles: true - ); - - // Act - (bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) = sut; - - // Assert - Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); - Assert.Equal(sut.ItemsPerPage, itemsPerPage); - Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); - Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); - Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing); - Assert.Equal(sut.ShouldRenderPdfAsImages, shouldRenderPdfAsImages); - Assert.Equal(sut.ShouldPreserveBookStyles, shouldPreserveBookStyles); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/ChangePasswordResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/ChangePasswordResponseTests.cs deleted file mode 100644 index 0b943997..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/ChangePasswordResponseTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.Authentication; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ChangePasswordResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingChangePasswordResponse_ShouldPreserveValues() - { - // Arrange - ChangePasswordResponse expected = new(true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ChangePasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingFalseChangePasswordResponse_ShouldPreserveFalse() - { - // Arrange - ChangePasswordResponse expected = new(false); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ChangePasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.False(actual.IsPasswordChanged); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - ChangePasswordResponse first = new(true); - ChangePasswordResponse second = new(true); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/LoginResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/LoginResponseTests.cs deleted file mode 100644 index 8b0830a3..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/LoginResponseTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.Authentication; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LoginResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingLoginResponse_ShouldPreserveValues() - { - // Arrange - Guid id = Guid.NewGuid(); - LoginResponse expected = new(id, "testUser", "jwt_token", true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LoginResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - Guid id = Guid.NewGuid(); - LoginResponse first = new(id, "testUser", "jwt_token", false); - LoginResponse second = new(id, "testUser", "jwt_token", false); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - Guid id = Guid.NewGuid(); - LoginResponse sut = new(id, "testUser", "jwt_token", true); - - // Act - (Guid sutId, string username, string token, bool usesTotp) = sut; - - // Assert - Assert.Equal(sut.Id, sutId); - Assert.Equal(sut.Username, username); - Assert.Equal(sut.Token, token); - Assert.Equal(sut.UsesTotp, usesTotp); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RecoverPasswordResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RecoverPasswordResponseTests.cs deleted file mode 100644 index f178b627..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RecoverPasswordResponseTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.Authentication; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class RecoverPasswordResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingRecoverPasswordResponse_ShouldPreserveValues() - { - // Arrange - RecoverPasswordResponse expected = new(true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RecoverPasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingFalseRecoverPasswordResponse_ShouldPreserveFalse() - { - // Arrange - RecoverPasswordResponse expected = new(false); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RecoverPasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.False(actual.IsPasswordReset); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - RecoverPasswordResponse first = new(true); - RecoverPasswordResponse second = new(true); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RegistrationResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RegistrationResponseTests.cs deleted file mode 100644 index 8e5b740c..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RegistrationResponseTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.Authentication; -using Lumina.Contracts.Responses.Authentication; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authentication; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class RegistrationResponseTests -{ - private readonly RegistrationResponseFixture _registrationResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingRegistrationResponse_ShouldPreserveValues() - { - // Arrange - RegistrationResponse expected = _registrationResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RegistrationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingRegistrationResponseWithNullTotpSecret_ShouldPreserveNull() - { - // Arrange - RegistrationResponse expected = _registrationResponseFixture.Create() with { TotpSecret = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RegistrationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.TotpSecret); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - RegistrationResponse sut = _registrationResponseFixture.Create(); - - // Act - (Guid sutId, string username, string? totpSecret) = sut; - - // Assert - Assert.Equal(sut.Id, sutId); - Assert.Equal(sut.Username, username); - Assert.Equal(sut.TotpSecret, totpSecret); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/AuthorizationResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/AuthorizationResponseTests.cs deleted file mode 100644 index 0ca9ec15..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/AuthorizationResponseTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class AuthorizationResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Serialize_WhenSerializingAuthorizationResponse_ShouldPreserveValues() - { - // Arrange - Guid userId = Guid.NewGuid(); - HashSet permissions = [AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers]; - AuthorizationResponse expected = new(userId, "Admin", permissions); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - - // Assert - Assert.Contains($"\"UserId\":\"{userId}\"", json, StringComparison.Ordinal); - Assert.Contains("\"Role\":\"Admin\"", json, StringComparison.Ordinal); - Assert.Contains("canViewUsers", json, StringComparison.Ordinal); - Assert.Contains("canDeleteUsers", json, StringComparison.Ordinal); - } - - [Fact] - public void Serialize_WhenSerializingAuthorizationResponse_ShouldSerializePermissionsAsCamelCaseStrings() - { - // Arrange - Guid userId = Guid.NewGuid(); - HashSet permissions = [AuthorizationPermission.CanRegisterUsers]; - AuthorizationResponse sut = new(userId, "Admin", permissions); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("canRegisterUsers", json, StringComparison.Ordinal); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - Guid userId = Guid.NewGuid(); - HashSet permissions = [AuthorizationPermission.None]; - AuthorizationResponse sut = new(userId, null, permissions); - - // Act - (Guid sutUserId, string? role, IReadOnlySet sutPermissions) = sut; - - // Assert - Assert.Equal(sut.UserId, sutUserId); - Assert.Equal(sut.Role, role); - Assert.Equal(sut.Permissions, sutPermissions); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/PermissionResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/PermissionResponseTests.cs deleted file mode 100644 index db6d35ff..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/PermissionResponseTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.Authorization; -using Lumina.Contracts.Responses.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PermissionResponseTests -{ - private readonly PermissionResponseFixture _permissionResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingPermissionResponse_ShouldPreserveValues() - { - // Arrange - PermissionResponse expected = _permissionResponseFixture.Create(permissionName: AuthorizationPermission.CanCreateLibraries); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PermissionResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingPermissionResponse_ShouldSerializePermissionNameAsCamelCaseString() - { - // Arrange - PermissionResponse sut = _permissionResponseFixture.Create(permissionName: AuthorizationPermission.CanCreateLibraries); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"PermissionName\":\"canCreateLibraries\"", json, StringComparison.Ordinal); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RolePermissionsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RolePermissionsResponseTests.cs deleted file mode 100644 index dd940302..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RolePermissionsResponseTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Authentication; -using Lumina.Contracts.Fixtures.Core.Responses.Authorization; -using Lumina.Contracts.Responses.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class RolePermissionsResponseTests -{ - private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingRolePermissionsResponse_ShouldPreserveValues() - { - // Arrange - RolePermissionsResponse expected = _rolePermissionsResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RolePermissionsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingRolePermissionsResponse_ShouldSerializePermissionNameAsCamelCaseString() - { - // Arrange - RolePermissionsResponse sut = _rolePermissionsResponseFixture.Create(permissions: - [ - new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers) - ]); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("canDeleteUsers", json, StringComparison.Ordinal); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RoleResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RoleResponseTests.cs deleted file mode 100644 index a1a2a27d..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RoleResponseTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.Authorization; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Authorization; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class RoleResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingRoleResponse_ShouldPreserveValues() - { - // Arrange - Guid id = Guid.NewGuid(); - RoleResponse expected = new(id, "Admin"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - RoleResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - Guid id = Guid.NewGuid(); - RoleResponse first = new(id, "Admin"); - RoleResponse second = new(id, "Admin"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs index c4899b3a..c52990bb 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs @@ -18,53 +18,6 @@ public class PaginatedResponseTests PropertyNameCaseInsensitive = true }; - [Fact] - public void PaginatedResponse_WhenConstructed_ShouldRequireAllProperties() - { - // Act - PaginatedResponse sut = new() - { - Data = [1, 2, 3], - CurrentPage = 1, - PerPage = 10, - Count = 3, - NumberOfPages = 1 - }; - - // Assert - Assert.Equal([1, 2, 3], sut.Data); - Assert.Equal(1, sut.CurrentPage); - Assert.Equal(10, sut.PerPage); - Assert.Equal(3, sut.Count); - Assert.Equal(1, sut.NumberOfPages); - } - - [Fact] - public void RoundTrip_WhenSerializingPaginatedResponse_ShouldPreserveValues() - { - // Arrange - PaginatedResponse expected = new() - { - Data = ["book1", "book2"], - CurrentPage = 2, - PerPage = 20, - Count = 2, - NumberOfPages = 1 - }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PaginatedResponse? actual = JsonSerializer.Deserialize>(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected.Data, actual.Data); - Assert.Equal(expected.CurrentPage, actual.CurrentPage); - Assert.Equal(expected.PerPage, actual.PerPage); - Assert.Equal(expected.Count, actual.Count); - Assert.Equal(expected.NumberOfPages, actual.NumberOfPages); - } - [Fact] public void Deserialize_WhenDataIsMissing_ShouldThrowJsonException() { @@ -74,25 +27,4 @@ public class PaginatedResponseTests // Act & Assert Assert.Throws(() => JsonSerializer.Deserialize>(json, _jsonOptions)); } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - PaginatedResponse first = new() - { - Data = [1, 2, 3], - CurrentPage = 1, - PerPage = 10, - Count = 3, - NumberOfPages = 1 - }; - PaginatedResponse second = first with { }; - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } } 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 c581247f..6df434f1 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs @@ -1,11 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using System; using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Common; @@ -16,14 +11,6 @@ namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Common; [ExcludeFromCodeCoverage] public class FileSystemTreeNodeResponseTests { - private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void Constructor_WhenInstantiatingNode_ShouldInitializeEmptyChildren() { @@ -34,56 +21,4 @@ public class FileSystemTreeNodeResponseTests Assert.NotNull(sut.Children); Assert.Empty(sut.Children); } - - [Fact] - public void Create_WhenCalled_ShouldReturnValidTreeNode() - { - // Act - FileSystemTreeNodeResponse sut = _fileSystemTreeNodeResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - Assert.False(string.IsNullOrWhiteSpace(sut.Name)); - Assert.Equal(FileSystemItemType.Directory, sut.ItemType); - } - - [Fact] - public void RoundTrip_WhenSerializingTreeNode_ShouldPreserveValues() - { - // Arrange - FileSystemTreeNodeResponse expected = _fileSystemTreeNodeResponseFixture.Create(maxDepth: 1, maxChildren: 2); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - FileSystemTreeNodeResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected.Path, actual.Path); - Assert.Equal(expected.Name, actual.Name); - Assert.Equal(expected.ItemType, actual.ItemType); - Assert.Equal(expected.Children.Count, actual.Children.Count); - } - - [Fact] - public void Serialize_WhenSerializingTreeNode_ShouldSerializeItemTypeAsCamelCaseString() - { - // Arrange - FileSystemTreeNodeResponse sut = new() - { - Path = @"C:\Media", - Name = "Media", - ItemType = FileSystemItemType.Directory, - IsExpanded = false, - ChildrenLoaded = true, - Children = [] - }; - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"ItemType\":\"directory\"", json, StringComparison.Ordinal); - } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Directories/DirectoryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Directories/DirectoryResponseTests.cs deleted file mode 100644 index de3182c5..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Directories/DirectoryResponseTests.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Directories; -using Lumina.Contracts.Responses.FileSystemManagement.Directories; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Directories; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class DirectoryResponseTests -{ - private readonly DirectoryResponseFixture _directoryResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidDirectoryResponse() - { - // Act - DirectoryResponse sut = _directoryResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - Assert.False(string.IsNullOrWhiteSpace(sut.Name)); - Assert.NotEmpty(sut.Items); - } - - [Fact] - public void RoundTrip_WhenSerializingDirectoryResponse_ShouldPreserveValues() - { - // Arrange - DirectoryResponse expected = _directoryResponseFixture.Create(itemCount: 2); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - DirectoryResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - DirectoryResponse sut = _directoryResponseFixture.Create(itemCount: 1); - - // Act - (string path, string name, System.DateTime dateCreated, System.DateTime dateModified, System.Collections.Generic.List items) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.Name, name); - Assert.Equal(sut.DateCreated, dateCreated); - Assert.Equal(sut.DateModified, dateModified); - Assert.Equal(sut.Items, items); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseTests.cs deleted file mode 100644 index be33dfd6..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.FileSystem; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class FileSystemTypeResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingFileSystemTypeResponse_ShouldPreserveValues() - { - // Arrange - FileSystemTypeResponse expected = new(PlatformType.Windows); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - FileSystemTypeResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingFileSystemTypeResponse_ShouldSerializePlatformTypeAsCamelCaseString() - { - // Arrange - FileSystemTypeResponse sut = new(PlatformType.Unix); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"PlatformType\":\"unix\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - FileSystemTypeResponse first = new(PlatformType.Windows); - FileSystemTypeResponse second = new(PlatformType.Windows); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Files/FileResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Files/FileResponseTests.cs deleted file mode 100644 index 6e2630b4..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Files/FileResponseTests.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Files; -using Lumina.Contracts.Responses.FileSystemManagement.Files; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Files; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class FileResponseTests -{ - private readonly FileResponseFixture _fileResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidFileResponse() - { - // Act - FileResponse sut = _fileResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - Assert.False(string.IsNullOrWhiteSpace(sut.Name)); - } - - [Fact] - public void RoundTrip_WhenSerializingFileResponse_ShouldPreserveValues() - { - // Arrange - FileResponse expected = _fileResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - FileResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - FileResponse sut = _fileResponseFixture.Create(); - - // Act - (string path, string name, System.DateTime dateCreated, System.DateTime dateModified, long size) = sut; - - // Assert - Assert.Equal(sut.Path, path); - Assert.Equal(sut.Name, name); - Assert.Equal(sut.DateCreated, dateCreated); - Assert.Equal(sut.DateModified, dateModified); - Assert.Equal(sut.Size, size); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathExistsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathExistsResponseTests.cs deleted file mode 100644 index ed857e8f..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathExistsResponseTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PathExistsResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingPathExistsResponse_ShouldPreserveValues() - { - // Arrange - PathExistsResponse expected = new(true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PathExistsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - PathExistsResponse first = new(true); - PathExistsResponse second = new(true); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSegmentResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSegmentResponseTests.cs deleted file mode 100644 index de0fcfe7..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSegmentResponseTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PathSegmentResponseTests -{ - private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidPathSegmentResponse() - { - // Act - PathSegmentResponse sut = _pathSegmentResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Path)); - } - - [Fact] - public void RoundTrip_WhenSerializingPathSegmentResponse_ShouldPreserveValues() - { - // Arrange - PathSegmentResponse expected = _pathSegmentResponseFixture.Create(path: @"C:\Media"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PathSegmentResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - PathSegmentResponse first = _pathSegmentResponseFixture.Create(path: @"C:\Media\Books"); - PathSegmentResponse second = _pathSegmentResponseFixture.Create(path: @"C:\Media\Books"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSeparatorResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSeparatorResponseTests.cs deleted file mode 100644 index ad35c768..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSeparatorResponseTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PathSeparatorResponseTests -{ - private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidPathSeparatorResponse() - { - // Act - PathSeparatorResponse sut = _pathSeparatorResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.False(string.IsNullOrWhiteSpace(sut.Separator)); - } - - [Fact] - public void RoundTrip_WhenSerializingPathSeparatorResponse_ShouldPreserveValues() - { - // Arrange - PathSeparatorResponse expected = _pathSeparatorResponseFixture.Create(separator: "\\"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PathSeparatorResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - PathSeparatorResponse first = _pathSeparatorResponseFixture.Create(separator: "/"); - PathSeparatorResponse second = _pathSeparatorResponseFixture.Create(separator: "/"); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathValidResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathValidResponseTests.cs deleted file mode 100644 index 8c887c9e..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathValidResponseTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.FileSystemManagement.Path; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PathValidResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingPathValidResponse_ShouldPreserveValues() - { - // Arrange - PathValidResponse expected = new(true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PathValidResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - PathValidResponse first = new(true); - PathValidResponse second = new(true); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseTests.cs deleted file mode 100644 index c385fb4e..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseTests.cs +++ /dev/null @@ -1,66 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnails; -using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Thumbnails; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ThumbnailResponseTests -{ - private readonly ThumbnailResponseFixture _thumbnailResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidThumbnailResponse() - { - // Act - ThumbnailResponse sut = _thumbnailResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEmpty(sut.Bytes); - } - - [Fact] - public void RoundTrip_WhenSerializingThumbnailResponse_ShouldPreserveValues() - { - // Arrange - ThumbnailResponse expected = _thumbnailResponseFixture.Create(type: ImageType.JPEG); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ThumbnailResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected.Type, actual.Type); - Assert.Equal(expected.Bytes, actual.Bytes); - } - - [Fact] - public void Serialize_WhenSerializingThumbnailResponse_ShouldSerializeTypeAsCamelCaseString() - { - // Arrange - ThumbnailResponse sut = _thumbnailResponseFixture.Create(type: ImageType.PNG); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Type\":\"png\"", json, StringComparison.Ordinal); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs deleted file mode 100644 index 38d65cd1..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LibraryResponseTests -{ - private readonly LibraryResponseFixture _libraryResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingLibraryResponse_ShouldPreserveValues() - { - // Arrange - LibraryResponse expected = _libraryResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LibraryResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingLibraryResponse_ShouldSerializeLibraryTypeAsCamelCaseString() - { - // Arrange - LibraryResponse sut = _libraryResponseFixture.Create(libraryType: LibraryType.Movie); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"LibraryType\":\"movie\"", json, StringComparison.Ordinal); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - LibraryResponse sut = _libraryResponseFixture.Create(); - - // Act - (Guid id, Guid userId, string title, LibraryType libraryType, List contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut; - - // Assert - Assert.Equal(sut.Id, id); - Assert.Equal(sut.UserId, userId); - Assert.Equal(sut.Title, title); - Assert.Equal(sut.LibraryType, libraryType); - Assert.Equal(sut.ContentLocations, contentLocations); - Assert.Equal(sut.CoverImage, coverImage); - Assert.Equal(sut.IsEnabled, isEnabled); - Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); - Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); - Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); - Assert.Equal(sut.CreatedOnUtc, createdOnUtc); - Assert.Equal(sut.UpdatedOnUtc, updatedOnUtc); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseTests.cs deleted file mode 100644 index f58bf1e2..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaLibraryScanJobProgressResponseTests -{ - private readonly MediaLibraryScanJobProgressResponseFixture _mediaLibraryScanJobProgressResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingMediaLibraryScanJobProgressResponse_ShouldPreserveValues() - { - // Arrange - MediaLibraryScanJobProgressResponse expected = _mediaLibraryScanJobProgressResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaLibraryScanJobProgressResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - MediaLibraryScanJobProgressResponse sut = _mediaLibraryScanJobProgressResponseFixture.Create(); - - // Act - (int completedItems, int totalItems, string currentOperation, decimal progressPercentage) = sut; - - // Assert - Assert.Equal(sut.CompletedItems, completedItems); - Assert.Equal(sut.TotalItems, totalItems); - Assert.Equal(sut.CurrentOperation, currentOperation); - Assert.Equal(sut.ProgressPercentage, progressPercentage); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseTests.cs deleted file mode 100644 index 5f10977c..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseTests.cs +++ /dev/null @@ -1,73 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; -using Lumina.Contracts.Responses.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaLibraryScanProgressResponseTests -{ - private readonly MediaLibraryScanProgressResponseFixture _mediaLibraryScanProgressResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingMediaLibraryScanProgressResponse_ShouldPreserveValues() - { - // Arrange - MediaLibraryScanProgressResponse expected = _mediaLibraryScanProgressResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaLibraryScanProgressResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingWithoutCurrentJobProgress_ShouldPreserveNull() - { - // Arrange - MediaLibraryScanProgressResponse expected = _mediaLibraryScanProgressResponseFixture.Create() with { CurrentJobProgress = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaLibraryScanProgressResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.CurrentJobProgress); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - MediaLibraryScanProgressResponse sut = _mediaLibraryScanProgressResponseFixture.Create(); - - // Act - (Guid scanId, Guid userId, Guid libraryId, int totalJobs, int completedJobs, MediaLibraryScanJobProgressResponse? currentJobProgress, string status, decimal overallProgressPercentage) = sut; - - // Assert - Assert.Equal(sut.ScanId, scanId); - Assert.Equal(sut.UserId, userId); - Assert.Equal(sut.LibraryId, libraryId); - Assert.Equal(sut.TotalJobs, totalJobs); - Assert.Equal(sut.CompletedJobs, completedJobs); - Assert.Equal(sut.CurrentJobProgress, currentJobProgress); - Assert.Equal(sut.Status, status); - Assert.Equal(sut.OverallProgressPercentage, overallProgressPercentage); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanResponseTests.cs deleted file mode 100644 index e7e9a048..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanResponseTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.MediaLibrary.Management; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class MediaLibraryScanResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingMediaLibraryScanResponse_ShouldPreserveValues() - { - // Arrange - Guid scanId = Guid.NewGuid(); - Guid libraryId = Guid.NewGuid(); - MediaLibraryScanResponse expected = new(scanId, libraryId); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - MediaLibraryScanResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - Guid scanId = Guid.NewGuid(); - Guid libraryId = Guid.NewGuid(); - MediaLibraryScanResponse sut = new(scanId, libraryId); - - // Act - (Guid sutScanId, Guid sutLibraryId) = sut; - - // Assert - Assert.Equal(sut.ScanId, sutScanId); - Assert.Equal(sut.LibraryId, sutLibraryId); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs deleted file mode 100644 index 4afd31eb..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class BookLiteResponseTests -{ - private readonly BookLiteResponseFixture _bookLiteResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingBookLiteResponse_ShouldPreserveValues() - { - // Arrange - BookLiteResponse expected = _bookLiteResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookLiteResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingBookLiteResponseWithNullValues_ShouldPreserveNulls() - { - // Arrange - BookLiteResponse expected = _bookLiteResponseFixture.Create(includeReleaseYear: false, includeCoverPath: false); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookLiteResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.ReleaseYear); - Assert.Null(actual.CoverPath); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - BookLiteResponse sut = _bookLiteResponseFixture.Create(); - - // Act - (Guid sutId, string title, int? releaseYear, string? coverPath) = sut; - - // Assert - Assert.Equal(sut.Id, sutId); - Assert.Equal(sut.Title, title); - Assert.Equal(sut.ReleaseYear, releaseYear); - Assert.Equal(sut.CoverPath, coverPath); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseTests.cs deleted file mode 100644 index 3bc196c4..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class BookResponseTests -{ - private readonly BookResponseFixture _bookResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingBookResponse_ShouldPreserveValues() - { - // Arrange - BookResponse expected = _bookResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - BookResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void Serialize_WhenSerializingBookResponse_ShouldSerializeEnumsAsCamelCaseStrings() - { - // Arrange - BookResponse sut = _bookResponseFixture.Create( - format: BookFormat.Paperback, - metadataStatus: MetadataStatus.Pending); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Format\":\"paperback\"", json, StringComparison.Ordinal); - Assert.Contains("\"MetadataStatus\":\"pending\"", json, StringComparison.Ordinal); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponseTests.cs deleted file mode 100644 index e071b39b..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingAvailabilityResponseTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingAvailabilityResponseTests -{ - private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new(); - - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void Create_WhenCalled_ShouldReturnValidReadingAvailabilityResponse() - { - // Act - ReadingAvailabilityResponse sut = _readingAvailabilityResponseFixture.Create(); - - // Assert - Assert.NotNull(sut); - Assert.NotEqual(System.Guid.Empty, sut.BookId); - Assert.NotEqual(System.Guid.Empty, sut.LibraryId); - Assert.True(sut.IsAvailable); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingAvailabilityResponse_ShouldPreserveValues() - { - // Arrange - ReadingAvailabilityResponse expected = _readingAvailabilityResponseFixture.Create(isAvailable: true, errorCode: null); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingAvailabilityResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingReadingAvailabilityResponseWithErrorCode_ShouldPreserveErrorCode() - { - // Arrange - ReadingAvailabilityResponse expected = _readingAvailabilityResponseFixture.Create(isAvailable: false, errorCode: "ReaderDisabled"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingAvailabilityResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - Assert.False(actual.IsAvailable); - Assert.Equal("ReaderDisabled", actual.ErrorCode); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponseTests.cs deleted file mode 100644 index cd1c5f53..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingManifestResponseTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingManifestResponseTests -{ - private readonly ReadingManifestResponseFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingReadingManifestResponse_ShouldPreserveValues() - { - // Arrange - ReadingManifestResponse expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingManifestResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponseTests.cs deleted file mode 100644 index 2abd9c69..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingSpineItemResponseTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingSpineItemResponseTests -{ - private readonly ReadingSpineItemResponseFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingReadingSpineItemResponse_ShouldPreserveValues() - { - // Arrange - ReadingSpineItemResponse expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingSpineItemResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponseTests.cs deleted file mode 100644 index 6c7421f6..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/ReadingTocEntryResponseTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class ReadingTocEntryResponseTests -{ - private readonly ReadingTocEntryResponseFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingReadingTocEntryResponse_ShouldPreserveValues() - { - // Arrange - ReadingTocEntryResponse expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - ReadingTocEntryResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryBookReaderResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryBookReaderResponseTests.cs deleted file mode 100644 index 18fa5042..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryBookReaderResponseTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.Plugins; -using Lumina.Contracts.Responses.Plugins; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LibraryBookReaderResponseTests -{ - private readonly LibraryBookReaderResponseFixture _fixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingLibraryBookReaderResponse_ShouldPreserveValues() - { - // Arrange - LibraryBookReaderResponse expected = _fixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LibraryBookReaderResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryMetadataProviderResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryMetadataProviderResponseTests.cs deleted file mode 100644 index f0f2c8dd..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryMetadataProviderResponseTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class LibraryMetadataProviderResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingProviderResponse_ShouldPreserveValues() - { - // Arrange - Guid pluginId = Guid.NewGuid(); - LibraryMetadataProviderResponse expected = new(pluginId, "OpenLibrary", true, 1); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - LibraryMetadataProviderResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - Guid pluginId = Guid.NewGuid(); - LibraryMetadataProviderResponse sut = new(pluginId, "OpenLibrary", false, 2); - - // Act - (Guid sutPluginId, string name, bool isEnabled, int rank) = sut; - - // Assert - Assert.Equal(sut.PluginId, sutPluginId); - Assert.Equal(sut.Name, name); - Assert.Equal(sut.IsEnabled, isEnabled); - Assert.Equal(sut.Rank, rank); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginResponseTests.cs deleted file mode 100644 index 23e94eff..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginResponseTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.Plugins; -using Lumina.Contracts.Responses.Plugins; -using Lumina.Domain.SharedKernel.Common.Enums.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PluginResponseTests -{ - private readonly PluginResponseFixture _pluginResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingPluginResponse_ShouldPreserveValues() - { - // Arrange - PluginResponse expected = _pluginResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PluginResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingFailedPluginResponse_ShouldPreserveLoadError() - { - // Arrange - PluginResponse expected = _pluginResponseFixture.Create( - loadStatus: PluginLoadStatus.FailedToLoad, - loadError: "Missing dependency"); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PluginResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(PluginLoadStatus.FailedToLoad, actual.LoadStatus); - Assert.Equal("Missing dependency", actual.LoadError); - } - - [Fact] - public void Serialize_WhenSerializingPluginResponse_ShouldSerializeLoadStatusAsCamelCaseString() - { - // Arrange - PluginResponse sut = _pluginResponseFixture.Create(loadStatus: PluginLoadStatus.Loaded); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"LoadStatus\":\"loaded\"", json, StringComparison.Ordinal); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingDescriptorResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingDescriptorResponseTests.cs deleted file mode 100644 index 66022abf..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingDescriptorResponseTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.Plugins; -using Lumina.Contracts.Responses.Plugins; -using Lumina.Domain.SharedKernel.Common.Enums.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -using System.Text.Json.Serialization; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PluginSettingDescriptorResponseTests -{ - private readonly PluginSettingDescriptorResponseFixture _pluginSettingDescriptorResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - - [Fact] - public void RoundTrip_WhenSerializingDescriptor_ShouldPreserveValues() - { - // Arrange - PluginSettingDescriptorResponse expected = _pluginSettingDescriptorResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PluginSettingDescriptorResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingDescriptorWithoutOptionalValues_ShouldPreserveNulls() - { - // Arrange - PluginSettingDescriptorResponse expected = _pluginSettingDescriptorResponseFixture.Create() with { DefaultValue = null, AllowedValues = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PluginSettingDescriptorResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.DefaultValue); - Assert.Null(actual.AllowedValues); - } - - [Fact] - public void Serialize_WhenSerializingDescriptor_ShouldSerializeTypeAsCamelCaseString() - { - // Arrange - PluginSettingDescriptorResponse sut = _pluginSettingDescriptorResponseFixture.Create(type: PluginSettingType.Number); - - // Act - string json = JsonSerializer.Serialize(sut, _jsonOptions); - - // Assert - Assert.Contains("\"Type\":\"number\"", json, StringComparison.Ordinal); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingsResponseTests.cs deleted file mode 100644 index fb8075b8..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingsResponseTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.Plugins; -using Lumina.Contracts.Responses.Plugins; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.Plugins; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class PluginSettingsResponseTests -{ - private readonly PluginSettingsResponseFixture _pluginSettingsResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingPluginSettingsResponse_ShouldPreserveValues() - { - // Arrange - PluginSettingsResponse expected = _pluginSettingsResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PluginSettingsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - // Assert - Assert.NotNull(actual); - Assert.Equivalent(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingPluginSettingsResponseWithNullSettings_ShouldPreserveNull() - { - // Arrange - PluginSettingsResponse expected = _pluginSettingsResponseFixture.Create() with { Settings = null }; - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - PluginSettingsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Null(actual.Settings); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/InitializationResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/InitializationResponseTests.cs deleted file mode 100644 index fa2a5569..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/InitializationResponseTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Responses.UsersManagement; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.UsersManagement; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class InitializationResponseTests -{ - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingInitializationResponse_ShouldPreserveValues() - { - // Arrange - InitializationResponse expected = new(true); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - InitializationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingFalseInitializationResponse_ShouldPreserveFalse() - { - // Arrange - InitializationResponse expected = new(false); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - InitializationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.False(actual.IsInitialized); - } - - [Fact] - public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() - { - // Arrange - InitializationResponse first = new(true); - InitializationResponse second = new(true); - - // Act - bool areEqual = first == second; - - // Assert - Assert.True(areEqual); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs deleted file mode 100644 index 2c0aeb92..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; -using Lumina.Contracts.Responses.UsersManagement.Settings; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Settings; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UserSettingsResponseTests -{ - private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUserSettingsResponse_ShouldPreserveValues() - { - // Arrange - Guid userId = Guid.NewGuid(); - UserSettingsResponse expected = _userSettingsResponseFixture.Create( - userId: userId, - isPaginationEnabled: true, - itemsPerPage: 50, - shouldIgnoreThePrefixForAlphaPicker: true, - isThemeCachingEnabled: true, - shouldAggregateMetadataWhenMissing: false - ); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UserSettingsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - Guid userId = Guid.NewGuid(); - UserSettingsResponse sut = _userSettingsResponseFixture.Create( - userId: userId, - isPaginationEnabled: false, - itemsPerPage: 25, - shouldIgnoreThePrefixForAlphaPicker: false, - isThemeCachingEnabled: false, - shouldAggregateMetadataWhenMissing: false, - shouldRenderPdfAsImages: true, - shouldPreserveBookStyles: true - ); - - // Act - (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing, bool shouldRenderPdfAsImages, bool shouldPreserveBookStyles) = sut; - - // Assert - Assert.Equal(sut.UserId, sutUserId); - Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); - Assert.Equal(sut.ItemsPerPage, itemsPerPage); - Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); - Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); - Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing); - Assert.Equal(sut.ShouldRenderPdfAsImages, shouldRenderPdfAsImages); - Assert.Equal(sut.ShouldPreserveBookStyles, shouldPreserveBookStyles); - } -} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Users/UserResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Users/UserResponseTests.cs deleted file mode 100644 index 1e8c9894..00000000 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Users/UserResponseTests.cs +++ /dev/null @@ -1,69 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Users; -using Lumina.Contracts.Responses.UsersManagement.Users; -using System; -using System.Diagnostics.CodeAnalysis; -using System.Text.Json; -#endregion - -namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Users; - -/// -/// Contains unit tests for the record. -/// -[ExcludeFromCodeCoverage] -public class UserResponseTests -{ - private readonly UserResponseFixture _userResponseFixture = new(); - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true - }; - - [Fact] - public void RoundTrip_WhenSerializingUserResponse_ShouldPreserveValues() - { - // Arrange - UserResponse expected = _userResponseFixture.Create(); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UserResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(expected, actual); - } - - [Fact] - public void RoundTrip_WhenSerializingUserResponseWithUpdatedOnUtc_ShouldPreserveValue() - { - // Arrange - DateTime updatedOnUtc = DateTime.UtcNow.AddDays(1); - UserResponse expected = _userResponseFixture.Create(updatedOnUtc: updatedOnUtc); - - // Act - string json = JsonSerializer.Serialize(expected, _jsonOptions); - UserResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.NotNull(actual); - Assert.Equal(updatedOnUtc, actual.UpdatedOnUtc); - } - - [Fact] - public void Deconstruct_WhenCalled_ShouldReturnAllProperties() - { - // Arrange - UserResponse sut = _userResponseFixture.Create(); - - // Act - (Guid sutId, string username, DateTime sutCreatedOnUtc, DateTime? sutUpdatedOnUtc) = sut; - - // Assert - Assert.Equal(sut.Id, sutId); - Assert.Equal(sut.Username, username); - Assert.Equal(sut.CreatedOnUtc, sutCreatedOnUtc); - Assert.Equal(sut.UpdatedOnUtc, sutUpdatedOnUtc); - } -} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs new file mode 100644 index 00000000..56797eba --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/AlbumConfigurationTests.cs @@ -0,0 +1,208 @@ +#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.Common; +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 AlbumConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public AlbumConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Albums", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(AlbumEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + IProperty artistIdProperty = entityType.GetProperty(nameof(AlbumEntity.ArtistId)); + IProperty libraryIdProperty = entityType.GetProperty(nameof(AlbumEntity.LibraryId)); + IProperty titleProperty = entityType.GetProperty(nameof(AlbumEntity.Title)); + 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 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 languageCodeProperty = entityType.GetProperty(nameof(AlbumEntity.LanguageCode)); + + // Assert + Assert.False(artistIdProperty.IsNullable); + Assert.False(libraryIdProperty.IsNullable); + Assert.False(titleProperty.IsNullable); + Assert.Equal(255, titleProperty.GetMaxLength()); + Assert.Equal(255, originalTitleProperty.GetMaxLength()); + Assert.Equal(2000, descriptionProperty.GetMaxLength()); + Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType); + Assert.Equal("TEXT", releaseCountryProperty.GetColumnType()); + Assert.Equal(2, releaseCountryProperty.GetMaxLength()); + Assert.Equal(typeof(MusicReleaseType?), releaseTypeProperty.ClrType); + Assert.Equal("TEXT", releaseTypeProperty.GetColumnType()); + Assert.Equal(50, releaseTypeProperty.GetMaxLength()); + Assert.Equal(typeof(MusicReleaseStatus?), releaseStatusProperty.ClrType); + Assert.Equal("TEXT", releaseStatusProperty.GetColumnType()); + Assert.Equal(50, releaseStatusProperty.GetMaxLength()); + Assert.Equal(typeof(MusicMediaFormat?), mediaFormatProperty.ClrType); + Assert.Equal("TEXT", mediaFormatProperty.GetColumnType()); + Assert.Equal(50, mediaFormatProperty.GetMaxLength()); + Assert.Equal(13, barcodeProperty.GetMaxLength()); + Assert.Equal(50, catalogNumberProperty.GetMaxLength()); + Assert.True(languageCodeProperty.IsNullable); + Assert.Equal(typeof(string), languageCodeProperty.ClrType); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureArtistRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + List foreignKeys = [.. entityType.GetForeignKeys()]; + + // Assert + IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity)); + Assert.Equal(nameof(AlbumEntity.ArtistId), artistForeignKey.Properties.Single().Name); + Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOwnedAlbumRatings() + { + // Arrange + IEntityType ratingEntityType = _context.Model.GetEntityTypes() + .Single(entityType => entityType.IsOwned() && entityType.ClrType == typeof(AudioRatingEntity) && entityType.GetTableName() == "AlbumRatings"); + + // Act + string? tableName = ratingEntityType.GetTableName(); + IReadOnlyList keyProperties = ratingEntityType.FindPrimaryKey()!.Properties; + IProperty valueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Value)); + IProperty maxValueProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.MaxValue)); + IProperty voteCountProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.VoteCount)); + IProperty sourceProperty = ratingEntityType.GetProperty(nameof(AudioRatingEntity.Source)); + + // Assert + Assert.Equal("AlbumRatings", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + Assert.Equal("decimal(3,2)", valueProperty.GetColumnType()); + Assert.False(valueProperty.IsNullable); + Assert.Equal("decimal(3,2)", maxValueProperty.GetColumnType()); + Assert.False(maxValueProperty.IsNullable); + Assert.True(voteCountProperty.IsNullable); + Assert.Equal(typeof(AudioRatingSource?), sourceProperty.ClrType); + Assert.Equal("TEXT", sourceProperty.GetColumnType()); + Assert.Equal(50, sourceProperty.GetMaxLength()); + Assert.True(sourceProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + List skipNavigations = [.. entityType.GetSkipNavigations()]; + + // Assert + Assert.Equal(2, skipNavigations.Count); + ISkipNavigation tagsNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Tags)); + Assert.Equal("AlbumTags", tagsNavigation.JoinEntityType.GetTableName()); + Assert.Equal(["AlbumId", "TagId"], tagsNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name)); + ISkipNavigation genresNavigation = Assert.Single(skipNavigations, navigation => navigation.Name == nameof(AlbumEntity.Genres)); + Assert.Equal("AlbumGenres", genresNavigation.JoinEntityType.GetTableName()); + Assert.Equal(["AlbumId", "GenreId"], genresNavigation.JoinEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexesOnArtistIdTitleAndLibraryIdTitle() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.ArtistId), nameof(AlbumEntity.Title)])); + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(AlbumEntity.LibraryId), nameof(AlbumEntity.Title)])); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(AlbumEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(AlbumEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(AlbumEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(AlbumEntity.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/ArtistConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/ArtistConfigurationTests.cs new file mode 100644 index 00000000..f18fc3f6 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/ArtistConfigurationTests.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +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 ArtistConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public ArtistConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Artists", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(ArtistEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + IProperty libraryIdProperty = entityType.GetProperty(nameof(ArtistEntity.LibraryId)); + IProperty nameProperty = entityType.GetProperty(nameof(ArtistEntity.Name)); + IProperty websiteProperty = entityType.GetProperty(nameof(ArtistEntity.Website)); + IProperty musicBrainzArtistIdProperty = entityType.GetProperty(nameof(ArtistEntity.MusicBrainzArtistId)); + + // Assert + Assert.False(libraryIdProperty.IsNullable); + Assert.False(nameProperty.IsNullable); + Assert.Equal(255, nameProperty.GetMaxLength()); + Assert.True(websiteProperty.IsNullable); + Assert.Equal(2048, websiteProperty.GetMaxLength()); + Assert.True(musicBrainzArtistIdProperty.IsNullable); + Assert.Equal(typeof(Guid?), musicBrainzArtistIdProperty.ClrType); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureContributorsRelationshipWithCascadeDelete() + { + // Arrange + IEntityType contributorEntityType = _context.Model.FindEntityType(typeof(ArtistContributorEntity))!; + + // Act + List foreignKeys = [.. contributorEntityType.GetForeignKeys()]; + + // Assert + IForeignKey artistForeignKey = Assert.Single(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(ArtistEntity)); + Assert.Equal(nameof(ArtistContributorEntity.ArtistId), artistForeignKey.Properties.Single().Name); + Assert.Equal(DeleteBehavior.Cascade, artistForeignKey.DeleteBehavior); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnLibraryIdAndName() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + IIndex uniquenessIndex = Assert.Single(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(ArtistEntity.LibraryId), nameof(ArtistEntity.Name)])); + Assert.True(uniquenessIndex.IsUnique); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(ArtistEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(ArtistEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(ArtistEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(ArtistEntity.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/TrackConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackConfigurationTests.cs new file mode 100644 index 00000000..2cbb25e2 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackConfigurationTests.cs @@ -0,0 +1,181 @@ +#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.Common; +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 TrackConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public TrackConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Tracks", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(TrackEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + IProperty pathProperty = entityType.GetProperty(nameof(TrackEntity.Path)); + IProperty titleProperty = entityType.GetProperty(nameof(TrackEntity.Title)); + IProperty originalTitleProperty = entityType.GetProperty(nameof(TrackEntity.OriginalTitle)); + IProperty descriptionProperty = entityType.GetProperty(nameof(TrackEntity.Description)); + IProperty releaseCountryProperty = entityType.GetProperty(nameof(TrackEntity.ReleaseCountry)); + 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)); + + // Assert + Assert.False(pathProperty.IsNullable); + Assert.Equal(2048, pathProperty.GetMaxLength()); + Assert.False(titleProperty.IsNullable); + Assert.Equal(255, titleProperty.GetMaxLength()); + Assert.Equal(255, originalTitleProperty.GetMaxLength()); + Assert.Equal(2000, descriptionProperty.GetMaxLength()); + Assert.Equal(typeof(ReleaseCountry?), releaseCountryProperty.ClrType); + Assert.Equal("TEXT", releaseCountryProperty.GetColumnType()); + Assert.Equal(2, releaseCountryProperty.GetMaxLength()); + Assert.Equal(50, scriptProperty.GetMaxLength()); + Assert.Equal(typeof(MusicKey?), keyProperty.ClrType); + Assert.Equal("TEXT", keyProperty.GetColumnType()); + Assert.Equal(50, keyProperty.GetMaxLength()); + Assert.Equal(50, audioCodecProperty.GetMaxLength()); + Assert.Equal(255, workProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAlbumRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + List foreignKeys = [.. entityType.GetForeignKeys()]; + + // Assert + IForeignKey albumForeignKey = Assert.Single(foreignKeys); + Assert.Equal(nameof(TrackEntity.AlbumId), albumForeignKey.Properties.Single().Name); + Assert.Equal(typeof(AlbumEntity), albumForeignKey.PrincipalEntityType.ClrType); + Assert.Equal(DeleteBehavior.Cascade, albumForeignKey.DeleteBehavior); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOwnedTypesForMoodsIsrcsAndRatings() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + List ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)]; + + // Assert + Assert.Equal(3, 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(AudioRatingEntity) && ownedType.GetTableName() == "TrackRatings"); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + List skipNavigations = [.. entityType.GetSkipNavigations()]; + + // Assert + Assert.Equal(2, skipNavigations.Count); + Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Tags) && navigation.JoinEntityType.GetTableName() == "TrackTags"); + Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(TrackEntity.Genres) && navigation.JoinEntityType.GetTableName() == "TrackGenres"); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexesOnAlbumIdTrackNumberAndLibraryIdPath() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.AlbumId), nameof(TrackEntity.TrackNumber)])); + IIndex pathIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackEntity.LibraryId), nameof(TrackEntity.Path)]))); + Assert.True(pathIndex.IsUnique); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(TrackEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.True(updatedOnUtcProperty.IsNullable); + } + + /// + /// Disposes the database context. + /// + public void Dispose() + { + _context.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackContributorConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackContributorConfigurationTests.cs new file mode 100644 index 00000000..95268f97 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TrackContributorConfigurationTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +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 TrackContributorConfigurationTests : IDisposable +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public TrackContributorConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("TrackContributors", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValue() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(TrackContributorEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!; + + // Act + IProperty trackIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.TrackId)); + IProperty mediaContributorIdProperty = entityType.GetProperty(nameof(TrackContributorEntity.MediaContributorId)); + IProperty roleProperty = entityType.GetProperty(nameof(TrackContributorEntity.Role)); + + // Assert + Assert.False(trackIdProperty.IsNullable); + Assert.False(mediaContributorIdProperty.IsNullable); + Assert.False(roleProperty.IsNullable); + Assert.Equal(typeof(MediaContributorRole), roleProperty.ClrType); + Assert.Equal("TEXT", roleProperty.GetColumnType()); + Assert.Equal(50, roleProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexAndContributorLookupIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + IIndex uniquenessIndex = Assert.Single(indexes.Where(index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.TrackId), nameof(TrackContributorEntity.MediaContributorId), nameof(TrackContributorEntity.Role)]))); + Assert.True(uniquenessIndex.IsUnique); + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(TrackContributorEntity.MediaContributorId)])); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TrackContributorEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(TrackContributorEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(TrackContributorEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.True(updatedOnUtcProperty.IsNullable); + } + + /// + /// Disposes the database context. + /// + public void Dispose() + { + _context.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/CollectionReconcilerTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/CollectionReconcilerTests.cs new file mode 100644 index 00000000..5c9da920 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/CollectionReconcilerTests.cs @@ -0,0 +1,289 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Common.Persistence; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Persistence; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CollectionReconcilerTests +{ + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly IsbnEntityFixture _isbnEntityFixture = new(); + private readonly BookContributorEntityFixture _bookContributorEntityFixture = new(); + + [Fact] + public void Reconcile_WhenAnItemIsNew_ShouldAddItToTheTrackedCollection() + { + // Arrange + List trackedTags = []; + List incomingTags = [_tagEntityFixture.Create(name: "jazz")]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + TagEntity addedTag = Assert.Single(trackedTags); + Assert.Same(incomingTags[0], addedTag); + } + + [Fact] + public void Reconcile_WhenATrackedItemIsAbsentFromTheIncomingSet_ShouldRemoveIt() + { + // Arrange + TagEntity removedTag = _tagEntityFixture.Create(name: "rock"); + TagEntity keptTag = _tagEntityFixture.Create(name: "jazz"); + List trackedTags = [removedTag, keptTag]; + List incomingTags = [_tagEntityFixture.Create(name: "jazz")]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + TagEntity keptTrackedTag = Assert.Single(trackedTags); + Assert.Same(keptTag, keptTrackedTag); + Assert.DoesNotContain(removedTag, trackedTags); + } + + [Fact] + public void Reconcile_WhenAMatchedItemDidNotChange_ShouldKeepTheSameTrackedInstance() + { + // Arrange + TagEntity trackedTag = _tagEntityFixture.Create(name: "rock"); + List trackedTags = [trackedTag]; + List incomingTags = [_tagEntityFixture.Create(name: "rock")]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + existingTag => existingTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (existingTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + TagEntity keptTrackedTag = Assert.Single(trackedTags); + Assert.Same(trackedTag, keptTrackedTag); + } + + [Fact] + public void Reconcile_WhenAMatchedItemChanged_ShouldReplaceOnlyThatItem() + { + // Arrange + IsbnEntity trackedIsbn = _isbnEntityFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn10); + IsbnEntity unchangedIsbn = _isbnEntityFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13); + List trackedIsbns = [trackedIsbn, unchangedIsbn]; + IsbnEntity incomingChangedIsbn = _isbnEntityFixture.Create(value: "978-3-16-148410-0", format: IsbnFormat.Isbn13); + IsbnEntity incomingUnchangedIsbn = _isbnEntityFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13); + List incomingIsbns = [incomingChangedIsbn, incomingUnchangedIsbn]; + + // Act + CollectionReconciler.Reconcile( + trackedIsbns, + incomingIsbns, + existingIsbn => existingIsbn.Value!, + incomingIsbn => incomingIsbn.Value!, + shouldReplace: (existingIsbn, incomingIsbn) => !existingIsbn.Equals(incomingIsbn), + createNew: incomingIsbn => incomingIsbn); + + // Assert + Assert.Equal(2, trackedIsbns.Count); + Assert.DoesNotContain(trackedIsbn, trackedIsbns); + Assert.Contains(incomingChangedIsbn, trackedIsbns); + IsbnEntity keptIsbn = trackedIsbns.Single(isbn => isbn.Value == unchangedIsbn.Value); + Assert.Same(unchangedIsbn, keptIsbn); + } + + [Fact] + public void Reconcile_WhenSeveralChangesAreRequested_ShouldApplyAddRemoveAndKeepInASinglePass() + { + // Arrange + BookContributorEntity removedContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Author); + BookContributorEntity keptContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Illustrator); + List trackedContributors = [removedContributor, keptContributor]; + BookContributorEntity incomingKeptContributor = _bookContributorEntityFixture.Create( + bookId: keptContributor.BookId, + mediaContributorId: keptContributor.MediaContributorId, + role: keptContributor.Role); + BookContributorEntity incomingNewContributor = _bookContributorEntityFixture.Create(role: MediaContributorRole.Translator); + List incomingContributors = [incomingKeptContributor, incomingNewContributor]; + + // Act + CollectionReconciler.Reconcile( + trackedContributors, + incomingContributors, + existingContributor => (existingContributor.MediaContributorId, existingContributor.Role), + incomingContributor => (incomingContributor.MediaContributorId, incomingContributor.Role), + shouldReplace: (existingContributor, incomingContributor) => false, + createNew: incomingContributor => incomingContributor); + + // Assert + Assert.Equal(2, trackedContributors.Count); + Assert.DoesNotContain(removedContributor, trackedContributors); + Assert.Same(keptContributor, trackedContributors.Single(contributor => contributor.MediaContributorId == keptContributor.MediaContributorId)); + Assert.Same(incomingNewContributor, trackedContributors.Single(contributor => contributor.MediaContributorId == incomingNewContributor.MediaContributorId)); + } + + [Fact] + public void Reconcile_WhenTheIncomingSetIsEmpty_ShouldRemoveEveryTrackedItem() + { + // Arrange + List trackedTags = [_tagEntityFixture.Create(name: "rock"), _tagEntityFixture.Create(name: "jazz")]; + List incomingTags = []; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + Assert.Empty(trackedTags); + } + + [Fact] + public void Reconcile_WhenTheTrackedCollectionIsEmpty_ShouldAddEveryIncomingItem() + { + // Arrange + List trackedTags = []; + List incomingTags = [_tagEntityFixture.Create(name: "rock"), _tagEntityFixture.Create(name: "jazz")]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + Assert.Equal(2, trackedTags.Count); + Assert.Same(incomingTags[0], trackedTags.Single(tag => tag.Name == "rock")); + Assert.Same(incomingTags[1], trackedTags.Single(tag => tag.Name == "jazz")); + } + + [Fact] + public void Reconcile_WhenTheTrackedCollectionHasDuplicateKeys_ShouldMatchTheFirstTrackedInstance() + { + // Arrange + TagEntity firstTrackedTag = _tagEntityFixture.Create(name: "rock"); + TagEntity secondTrackedTag = _tagEntityFixture.Create(name: "rock"); + List trackedTags = [firstTrackedTag, secondTrackedTag]; + List incomingTags = [_tagEntityFixture.Create(name: "rock")]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + Assert.Equal(2, trackedTags.Count); + Assert.Same(firstTrackedTag, trackedTags[0]); + Assert.Same(secondTrackedTag, trackedTags[1]); + } + + [Fact] + public void Reconcile_WhenTheIncomingCollectionHasDuplicateNewKeys_ShouldAddOnlyOneItem() + { + // Arrange + List trackedTags = []; + TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock"); + TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock"); + List incomingTags = [firstIncomingTag, secondIncomingTag]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => false, + createNew: incomingTag => incomingTag); + + // Assert + TagEntity addedTag = Assert.Single(trackedTags); + Assert.Same(firstIncomingTag, addedTag); + } + + [Fact] + public void Reconcile_WhenAReplacedItemIsRematchedByALaterIncomingItem_ShouldReuseTheReplacement() + { + // Arrange + TagEntity trackedTag = _tagEntityFixture.Create(name: "rock"); + List trackedTags = [trackedTag]; + TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock"); + TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock"); + List incomingTags = [firstIncomingTag, secondIncomingTag]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + existingTag => existingTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (existingTag, incomingTag) => !ReferenceEquals(existingTag, incomingTag), + createNew: incomingTag => incomingTag); + + // Assert + TagEntity replacedTag = Assert.Single(trackedTags); + Assert.Same(secondIncomingTag, replacedTag); + Assert.DoesNotContain(trackedTags, trackedItem => ReferenceEquals(trackedItem, firstIncomingTag)); + } + + [Fact] + public void Reconcile_WhenANewItemIsAddedAndALaterIncomingItemReplacesIt_ShouldKeepASingleItem() + { + // Arrange + List trackedTags = []; + TagEntity firstIncomingTag = _tagEntityFixture.Create(name: "rock"); + TagEntity secondIncomingTag = _tagEntityFixture.Create(name: "rock"); + List incomingTags = [firstIncomingTag, secondIncomingTag]; + + // Act + CollectionReconciler.Reconcile( + trackedTags, + incomingTags, + trackedTag => trackedTag.Name!, + incomingTag => incomingTag.Name!, + shouldReplace: (trackedTag, incomingTag) => !ReferenceEquals(trackedTag, incomingTag), + createNew: incomingTag => incomingTag); + + // Assert + // The item added for the first occurrence is indexed, so the second occurrence matches it instead of adding a duplicate. + TagEntity trackedTag = Assert.Single(trackedTags); + Assert.Same(secondIncomingTag, trackedTag); + Assert.DoesNotContain(trackedTags, trackedItem => ReferenceEquals(trackedItem, firstIncomingTag)); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/EditableValuesCopierTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/EditableValuesCopierTests.cs new file mode 100644 index 00000000..094bf835 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/EditableValuesCopierTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Persistence; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EditableValuesCopierTests +{ + private readonly LuminaDbContext _mockContext = Create.MockedDbContextFor(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + + [Fact] + public async Task CopyEditableValues_WhenCalled_ShouldCopyTheEditableScalarValuesOntoTheTrackedEntity() + { + // Arrange + ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(trackedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, name: "Updated Artist", includeAlbums: false, includeContributors: false); + incomingArtist.Website = "https://updated.example.com"; + + // Act + EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist); + + // Assert + Assert.Equal("Updated Artist", trackedArtist.Name); + Assert.Equal("https://updated.example.com", trackedArtist.Website); + } + + [Fact] + public async Task CopyEditableValues_WhenCalled_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + DateTime storedUpdatedOnUtc = new(2021, 1, 2, 3, 4, 5, DateTimeKind.Utc); + Guid storedUpdatedBy = Guid.NewGuid(); + ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + trackedArtist.CreatedOnUtc = storedCreatedOnUtc; + trackedArtist.CreatedBy = storedCreatedBy; + trackedArtist.UpdatedOnUtc = storedUpdatedOnUtc; + trackedArtist.UpdatedBy = storedUpdatedBy; + _mockContext.Artists.Add(trackedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, includeAlbums: false, includeContributors: false); + incomingArtist.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + incomingArtist.CreatedBy = Guid.NewGuid(); + incomingArtist.UpdatedOnUtc = DateTime.UtcNow; + incomingArtist.UpdatedBy = Guid.NewGuid(); + + // Act + EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist); + + // Assert + Assert.Equal(storedCreatedOnUtc, trackedArtist.CreatedOnUtc); + Assert.Equal(storedCreatedBy, trackedArtist.CreatedBy); + Assert.Equal(storedUpdatedOnUtc, trackedArtist.UpdatedOnUtc); + Assert.Equal(storedUpdatedBy, trackedArtist.UpdatedBy); + } + + [Fact] + public async Task CopyEditableValues_WhenNoEditableValueChanged_ShouldNotMarkAnyEditablePropertyAsModified() + { + // Arrange + ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(trackedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity incomingArtist = _artistEntityFixture.Create(id: trackedArtist.Id, includeAlbums: false, includeContributors: false); + incomingArtist.Name = trackedArtist.Name; + incomingArtist.Website = trackedArtist.Website; + incomingArtist.MusicBrainzArtistId = trackedArtist.MusicBrainzArtistId; + incomingArtist.LibraryId = trackedArtist.LibraryId; + + // Act + EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist); + + // Assert + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Name).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Website).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.MusicBrainzArtistId).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.LibraryId).IsModified); + // The primary key and the audit columns are owned by the persistence medium, so the copy never touches them either. + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.Id).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.CreatedOnUtc).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.CreatedBy).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.UpdatedOnUtc).IsModified); + Assert.False(_mockContext.Entry(trackedArtist).Property(artist => artist.UpdatedBy).IsModified); + } + + [Theory] + [InlineData(false)] // the incoming entity carries a different, non-empty key + [InlineData(true)] // the incoming entity carries an unset key + public async Task CopyEditableValues_WhenTheIncomingKeyDoesNotMatchTheTrackedOne_ShouldPreserveTheTrackedIdentity(bool useUnsetKey) + { + // Arrange + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + ArtistEntity trackedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + trackedArtist.CreatedOnUtc = storedCreatedOnUtc; + trackedArtist.CreatedBy = storedCreatedBy; + trackedArtist.UpdatedOnUtc = null; + trackedArtist.UpdatedBy = null; + _mockContext.Artists.Add(trackedArtist); + await _mockContext.SaveChangesAsync(); + Guid trackedArtistId = trackedArtist.Id; + + // The incoming entity carries a key that does not match the tracked one, a changed editable value, and hostile audit values. + Guid incomingId = useUnsetKey ? Guid.Empty : Guid.NewGuid(); + ArtistEntity incomingArtist = _artistEntityFixture.Create(id: incomingId, name: "Updated Artist", includeAlbums: false, includeContributors: false); + incomingArtist.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + incomingArtist.CreatedBy = Guid.NewGuid(); + incomingArtist.UpdatedOnUtc = DateTime.UtcNow; + incomingArtist.UpdatedBy = Guid.NewGuid(); + + // Act + EditableValuesCopier.CopyEditableValues(_mockContext, trackedArtist, incomingArtist); + + // Assert + // The stored identity is never retargeted by the incoming key, the audit columns are untouched, and the editable values are still copied. + Assert.Equal(trackedArtistId, trackedArtist.Id); + Assert.NotEqual(incomingId, trackedArtist.Id); + Assert.Equal("Updated Artist", trackedArtist.Name); + Assert.Equal(storedCreatedOnUtc, trackedArtist.CreatedOnUtc); + Assert.Equal(storedCreatedBy, trackedArtist.CreatedBy); + Assert.Null(trackedArtist.UpdatedOnUtc); + Assert.Null(trackedArtist.UpdatedBy); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/SharedReferenceResolverTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/SharedReferenceResolverTests.cs new file mode 100644 index 00000000..a79fc8bf --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Persistence/SharedReferenceResolverTests.cs @@ -0,0 +1,283 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Persistence; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SharedReferenceResolverTests +{ + private readonly LuminaDbContext _mockContext = Create.MockedDbContextFor(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + + [Fact] + public async Task ResolveAsync_WhenANameIsNotStored_ShouldReturnTheIncomingInstance() + { + // Arrange + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(resolveResult.IsFailure); + Assert.Same(incomingTag, resolveResult.Value["jazz"]); + } + + [Fact] + public async Task ResolveAsync_WhenANameIsAlreadyStoredAndTracked_ShouldReturnTheTrackedInstance() + { + // Arrange + TagEntity storedTag = _tagEntityFixture.Create(name: "jazz"); + _mockContext.Set().Add(storedTag); + await _mockContext.SaveChangesAsync(); + + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(resolveResult.IsFailure); + Assert.Same(storedTag, resolveResult.Value["jazz"]); + } + + [Fact] + public async Task ResolveAsync_WhenANameIsAlreadyStoredButNotTracked_ShouldLoadTheStoredInstanceFromStorage() + { + // Arrange + TagEntity storedTag = _tagEntityFixture.Create(name: "jazz"); + _mockContext.Set().Add(storedTag); + await _mockContext.SaveChangesAsync(); + + // Detach the stored row, so that the resolution cannot take the tracked shortcut and must read it from the storage medium. + _mockContext.ChangeTracker.Clear(); + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(resolveResult.IsFailure); + TagEntity resolvedTag = resolveResult.Value["jazz"]; + // A different instance than the incoming one proves the row was materialized from the storage medium instead of the tracked shortcut. + Assert.NotSame(incomingTag, resolvedTag); + Assert.Equal("jazz", resolvedTag.Name); + } + + [Fact] + public async Task ResolveAsync_WhenTheSameNameAppearsMoreThanOnce_ShouldCollapseItToASingleInstance() + { + // Arrange + TagEntity firstTag = _tagEntityFixture.Create(name: "jazz"); + TagEntity secondTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(resolveResult.IsFailure); + Assert.Single(resolveResult.Value); + Assert.Same(firstTag, resolveResult.Value["jazz"]); + } + + [Fact] + public async Task ResolveAsync_WhenThereAreNoIncomingEntities_ShouldReturnAnEmptyDictionary() + { + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(resolveResult.IsFailure); + Assert.Empty(resolveResult.Value); + } + + [Fact] + public async Task ReconcileAsync_WhenCalledWithAnotherSharedReferenceType_ShouldReconcileItTheSameWay() + { + // Arrange + List trackedGenres = [_genreEntityFixture.Create(name: "rock")]; + GenreEntity incomingGenre = _genreEntityFixture.Create(name: "jazz"); + + // Act + Result result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedGenres, [incomingGenre], Errors.Metadata.GenreNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(incomingGenre, Assert.Single(trackedGenres)); + } + + [Fact] + public async Task Normalize_WhenCalled_ShouldMapEveryEntityToItsResolvedInstance() + { + // Arrange + TagEntity firstTag = _tagEntityFixture.Create(name: "jazz"); + TagEntity secondTag = _tagEntityFixture.Create(name: "jazz"); + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Act + IReadOnlyCollection normalizedTags = SharedReferenceResolver.Normalize([firstTag, secondTag], resolveResult.Value); + + // Assert + TagEntity normalizedTag = Assert.Single(normalizedTags); + Assert.Same(firstTag, normalizedTag); + } + + [Fact] + public async Task ReconcileAsync_WhenANameIsNew_ShouldAddItToTheTrackedCollection() + { + // Arrange + List trackedTags = []; + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(incomingTag, Assert.Single(trackedTags)); + } + + [Fact] + public async Task ReconcileAsync_WhenANameIsAlreadyStored_ShouldReuseTheStoredInstance() + { + // Arrange + TagEntity storedTag = _tagEntityFixture.Create(name: "jazz"); + _mockContext.Set().Add(storedTag); + await _mockContext.SaveChangesAsync(); + + List trackedTags = []; + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(storedTag, Assert.Single(trackedTags)); + } + + [Fact] + public async Task ReconcileAsync_WhenATrackedNameIsMissingFromTheIncomingSet_ShouldRemoveIt() + { + // Arrange + TagEntity removedTag = _tagEntityFixture.Create(name: "rock"); + TagEntity keptTag = _tagEntityFixture.Create(name: "jazz"); + List trackedTags = [removedTag, keptTag]; + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(keptTag, Assert.Single(trackedTags)); + Assert.DoesNotContain(removedTag, trackedTags); + } + + [Fact] + public async Task ReconcileAsync_WhenTheSameNewNameAppearsMoreThanOnce_ShouldTrackASingleInstance() + { + // Arrange + List trackedTags = []; + TagEntity firstTag = _tagEntityFixture.Create(name: "jazz"); + TagEntity secondTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [firstTag, secondTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Same(firstTag, Assert.Single(trackedTags)); + } + + [Fact] + public async Task ResolveAsync_WhenANameIsNull_ShouldReturnNameCannotBeEmptyError() + { + // Arrange + TagEntity incomingTag = _tagEntityFixture.Create(includeName: false); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.True(resolveResult.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, resolveResult.FirstError); + } + + [Fact] + public async Task ResolveAsync_WhenANameIsWhitespace_ShouldReturnNameCannotBeEmptyError() + { + // Arrange + TagEntity incomingTag = _tagEntityFixture.Create(name: " "); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.True(resolveResult.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, resolveResult.FirstError); + } + + [Fact] + public async Task ResolveAsync_WhenTheNameIsAlreadyTrackedButNotStored_ShouldReturnTheTrackedInstance() + { + // Arrange + TagEntity trackedTag = _tagEntityFixture.Create(name: "jazz"); + _mockContext.Set().Add(trackedTag); + + TagEntity incomingTag = _tagEntityFixture.Create(name: "jazz"); + + // Act + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.False(resolveResult.IsFailure); + Assert.Same(trackedTag, resolveResult.Value["jazz"]); + } + + [Fact] + public async Task ReconcileAsync_WhenANameIsNull_ShouldReturnNameCannotBeEmptyErrorWithoutChangingTheTrackedCollection() + { + // Arrange + List trackedTags = []; + TagEntity incomingTag = _tagEntityFixture.Create(includeName: false); + + // Act + Result result = await SharedReferenceResolver.ReconcileAsync(_mockContext, trackedTags, [incomingTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Metadata.TagNameCannotBeEmpty, result.FirstError); + Assert.Empty(trackedTags); + } + + [Fact] + public async Task Normalize_WhenAnEntityCannotBeResolved_ShouldSkipIt() + { + // Arrange + TagEntity namedTag = _tagEntityFixture.Create(name: "jazz"); + TagEntity unnamedTag = _tagEntityFixture.Create(includeName: false); + Result> resolveResult = await SharedReferenceResolver.ResolveAsync(_mockContext, [namedTag], Errors.Metadata.TagNameCannotBeEmpty, CancellationToken.None); + + // Act + IReadOnlyCollection normalizedTags = SharedReferenceResolver.Normalize([namedTag, unnamedTag], resolveResult.Value); + + // Assert + Assert.Same(namedTag, Assert.Single(normalizedTags)); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs index 16fdd5a1..cf473916 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/PermissionRepositoryTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; @@ -83,25 +85,25 @@ public class PermissionRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(3, result.Value.Count()); - Assert.Equal(permissions, result.Value); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(permissions, result.Value.Data); } [Fact] public async Task GetAllAsync_WhenNoPermissionsExist_ShouldReturnEmptyList() { // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Empty(result.Value); + Assert.Empty(result.Value.Data); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs index 849c5353..dae2e9d2 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.Repositories.Authorization; @@ -111,25 +113,25 @@ public class RoleRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(2, result.Value.Count()); - Assert.Equal(roles, result.Value); + Assert.Equal(2, result.Value.Data.Count); + Assert.Equal(roles, result.Value.Data); } [Fact] public async Task GetAllAsync_WhenNoRolesExist_ShouldReturnEmptyList() { // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Empty(result.Value); + Assert.Empty(result.Value.Data); } [Fact] @@ -137,6 +139,8 @@ public class RoleRepositoryTests { // Arrange RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); + RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(role: role, roleId: role.Id); + role.RolePermissions = [rolePermission]; _mockContext.Roles.Add(role); await _mockContext.SaveChangesAsync(); @@ -147,7 +151,12 @@ public class RoleRepositoryTests // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(role, result.Value); + Assert.Equal(role.Id, result.Value!.Id); + Assert.Equal("Admin", result.Value.RoleName); + RolePermissionEntity loadedPermission = Assert.Single(result.Value.RolePermissions); + Assert.Equal(rolePermission.PermissionId, loadedPermission.PermissionId); + Assert.NotNull(loadedPermission.Permission); + Assert.Equal(rolePermission.Permission.Id, loadedPermission.Permission.Id); } [Fact] @@ -167,20 +176,26 @@ public class RoleRepositoryTests // Arrange RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(); RoleEntity role = rolePermission.Role; + role.RolePermissions = [rolePermission]; _mockContext.Roles.Add(role); await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(role.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(role.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(role.Id, result.Value.Id); + Assert.Equal(role.Id, result.Value!.Id); Assert.Equal(role.RoleName, result.Value.RoleName); Assert.Equal(role.CreatedOnUtc, result.Value.CreatedOnUtc); Assert.Equal(role.CreatedBy, result.Value.CreatedBy); + RolePermissionEntity loadedPermission = Assert.Single(result.Value.RolePermissions); + Assert.Equal(rolePermission.PermissionId, loadedPermission.PermissionId); + Assert.Equal(role.Id, loadedPermission.RoleId); + Assert.NotNull(loadedPermission.Permission); + Assert.Equal(rolePermission.Permission.Id, loadedPermission.Permission.Id); } [Fact] @@ -190,7 +205,7 @@ public class RoleRepositoryTests Guid nonExistentId = Guid.NewGuid(); // Act - Result result = await _sut.GetByIdAsync(nonExistentId, CancellationToken.None); + Result result = await _sut.GetByIdAsync(nonExistentId, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -263,8 +278,47 @@ public class RoleRepositoryTests EntityEntry? updatedEntry = _mockContext.ChangeTracker.Entries() .FirstOrDefault(e => e.Entity.Id == existingRole.Id); Assert.NotNull(updatedEntry); - Assert.Single(updatedEntry!.Entity.RolePermissions); - Assert.Equal(newRolePermission, updatedEntry.Entity.RolePermissions.First()); + RolePermissionEntity storedPermission = Assert.Single(updatedEntry!.Entity.RolePermissions); + Assert.Equal(newRolePermission.PermissionId, storedPermission.PermissionId); + Assert.Equal(existingRole.Id, storedPermission.RoleId); + } + + [Fact] + public async Task UpdateAsync_WhenAPermissionIsStillPresent_ShouldKeepItsIdentityAndAuditColumns() + { + // Arrange + RolePermissionEntity existingRolePermission = _rolePermissionEntityFixture.Create(); + DateTime keptCreatedOnUtc = new(2020, 5, 6, 7, 8, 9, DateTimeKind.Utc); + existingRolePermission.CreatedOnUtc = keptCreatedOnUtc; + RoleEntity existingRole = existingRolePermission.Role; + existingRole.RolePermissions = [existingRolePermission]; + + _mockContext.Roles.Add(existingRole); + await _mockContext.SaveChangesAsync(); + + RolePermissionEntity incomingRolePermission = _rolePermissionEntityFixture.Create( + roleId: existingRole.Id, + role: existingRole, + permissionId: existingRolePermission.PermissionId, + permission: existingRolePermission.Permission); + + RoleEntity updatedRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: existingRole.RoleName, rolePermissions: [incomingRolePermission], includeRolePermissions: true, createdBy: existingRole.CreatedBy, createdOnUtc: existingRole.CreatedOnUtc); + updatedRole.UpdatedOnUtc = DateTime.UtcNow; + updatedRole.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? updatedEntry = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(e => e.Entity.Id == existingRole.Id); + Assert.NotNull(updatedEntry); + RolePermissionEntity retainedPermission = Assert.Single(updatedEntry!.Entity.RolePermissions); + Assert.Equal(existingRolePermission.Id, retainedPermission.Id); + Assert.Equal(keptCreatedOnUtc, retainedPermission.CreatedOnUtc); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs similarity index 66% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs rename to tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index 7152cdab..c4375abc 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -4,13 +4,14 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DTO.Filtering; using Lumina.Application.Fixtures.Common.DTO.Pagination; -using Lumina.DataAccess.Core.Repositories.Books; +using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -28,7 +29,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books; +namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary; /// /// Contains unit tests for the class. @@ -96,6 +97,50 @@ public class BookRepositoryTests Assert.Single(_mockContext.ChangeTracker.Entries()); // Only the existing book should be in the context. } + [Fact] + public async Task InsertAsync_WhenAnotherBookOfTheSameLibraryHasTheSamePath_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity existingBook = _bookEntityFixture.Create(); + existingBook.LibraryId = libraryId; + existingBook.Path = "/books/existing.epub"; + _mockContext.Books.Add(existingBook); + await _mockContext.SaveChangesAsync(); + + BookEntity bookModel = _bookEntityFixture.Create(); + bookModel.LibraryId = libraryId; + bookModel.Path = "/books/existing.epub"; + + // Act + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.WrittenContent.BookAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasABookWithTheSamePath_ShouldAddBookToContextAndReturnCreated() + { + // Arrange + BookEntity existingBook = _bookEntityFixture.Create(); + existingBook.Path = "/books/existing.epub"; + _mockContext.Books.Add(existingBook); + await _mockContext.SaveChangesAsync(); + + BookEntity bookModel = _bookEntityFixture.Create(); + bookModel.LibraryId = Guid.NewGuid(); + bookModel.Path = "/books/existing.epub"; + + // Act + Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + } + [Fact] public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes() { @@ -151,54 +196,66 @@ public class BookRepositoryTests } [Fact] - public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooks() + public async Task GetAllAsync_WhenCalled_ShouldReturnAllBooksOfTheLibrary() { // Arrange + Guid libraryId = Guid.NewGuid(); List books = _bookEntityFixture.CreateMany(3); + foreach (BookEntity book in books) + book.LibraryId = libraryId; _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(filterModel: filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(3, result.Value.Count()); - Assert.Equal(books, result.Value); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal([.. books.OrderBy(book => book.Id)], [.. result.Value.Data.OrderBy(book => book.Id)]); } [Fact] public async Task GetAllAsync_WhenNoBooksExist_ShouldReturnEmptyList() { + // Arrange + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(); + // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(filterModel: filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Empty(result.Value); + Assert.Empty(result.Value.Data); } [Fact] - public async Task GetAllAsync_WhenCalled_ShouldIncludeRelatedEntities() + public async Task GetAllAsync_WhenPaginationIsNotProvided_ShouldIncludeRelatedEntities() { // Arrange + Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(filterModel: filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Single(result.Value); - BookEntity retrievedBook = result.Value.First(); + Assert.Single(result.Value.Data); + BookEntity retrievedBook = result.Value.Data.First(); Assert.Equal(2, retrievedBook.Tags.Count); Assert.Equal(2, retrievedBook.Genres.Count); Assert.Equal(2, retrievedBook.ISBNs.Count); @@ -384,7 +441,7 @@ public class BookRepositoryTests .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) + .Include(book => book.Contributors) .FirstOrDefaultAsync(book => book.Id == storedBook.Id); Assert.NotNull(retrievedBook); Assert.Equal("Updated Title", retrievedBook!.Title); @@ -398,6 +455,33 @@ public class BookRepositoryTests Assert.Equal(storedCreatedBy, retrievedBook.CreatedBy); } + [Fact] + public async Task UpdateAsync_WhenStoredBookHasArtwork_ShouldPreserveTheStoredArtwork() + { + // Arrange + BookEntity storedBook = _bookEntityFixture.Create(); + storedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: storedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched, fileName: "cover.jpg")]; + _mockContext.Books.Add(storedBook); + await _mockContext.SaveChangesAsync(); + + BookEntity data = _bookEntityFixture.Create(id: storedBook.Id); + data.Title = "Updated Title"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + BookEntity? retrievedBook = await _mockContext.Books + .Include(book => book.Artwork) + .FirstOrDefaultAsync(book => book.Id == storedBook.Id); + Assert.NotNull(retrievedBook); + BookArtworkEntity retrievedArtwork = Assert.Single(retrievedBook!.Artwork); + Assert.Equal("cover.jpg", retrievedArtwork.FileName); + Assert.Equal(ArtworkStatus.Enriched, retrievedArtwork.Status); + } + [Fact] public async Task UpdateAsync_WhenDataContainsExistingTagAndGenreNames_ShouldReuseTheStoredTagAndGenreEntities() { @@ -441,14 +525,14 @@ public class BookRepositoryTests BookEntity storedBook = _bookEntityFixture.Create(); storedBook.ISBNs = [_isbnEntityFixture.Create(value: "9780395272237", format: IsbnFormat.Isbn13)]; storedBook.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)]; - storedBook.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, roleCategory: MediaContributorRoleCategory.Author)]; + storedBook.Contributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, role: MediaContributorRole.Author)]; _mockContext.Books.Add(storedBook); await _mockContext.SaveChangesAsync(); BookEntity data = _bookEntityFixture.Create(id: storedBook.Id); data.ISBNs = [_isbnEntityFixture.Create(value: "9780261102693", format: IsbnFormat.Isbn13)]; data.Ratings = [_bookRatingEntityFixture.Create(value: 3.5M, maxValue: 5, source: BookRatingSource.Amazon, voteCount: 50)]; - data.BookContributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), roleCategory: MediaContributorRoleCategory.Illustrator)]; + data.Contributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Illustrator)]; // Act Result result = await _sut.UpdateAsync(data, CancellationToken.None); @@ -459,19 +543,19 @@ public class BookRepositoryTests BookEntity? retrievedBook = await _mockContext.Books .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) + .Include(book => book.Contributors) .FirstOrDefaultAsync(book => book.Id == storedBook.Id); Assert.NotNull(retrievedBook); IsbnEntity retrievedIsbn = Assert.Single(retrievedBook!.ISBNs); BookRatingEntity retrievedRating = Assert.Single(retrievedBook.Ratings); - BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.BookContributors); + BookContributorEntity retrievedContributor = Assert.Single(retrievedBook.Contributors); Assert.Equal("9780261102693", retrievedIsbn.Value); Assert.Equal(3.5M, retrievedRating.Value); - Assert.Equal(MediaContributorRoleCategory.Illustrator, retrievedContributor.RoleCategory); + Assert.Equal(MediaContributorRole.Illustrator, retrievedContributor.Role); } [Fact] - public async Task GetPaginatedAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks() + public async Task GetAllAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedBooks() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -485,7 +569,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -497,14 +581,14 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() + public async Task GetAllAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() { // Arrange PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); BaseFilterDto filter = _baseFilterDtoFixture.Create(); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -512,14 +596,14 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() + public async Task GetAllAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() { // Arrange PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -527,7 +611,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks() + public async Task GetAllAsync_WhenPaginationDataIsNull_ShouldReturnAllBooks() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -540,7 +624,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -552,7 +636,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks() + public async Task GetAllAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingBooks() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -569,7 +653,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship"); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -579,7 +663,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata() + public async Task GetAllAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -593,7 +677,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -605,7 +689,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder() + public async Task GetAllAsync_WhenSortByTitleDescending_ShouldReturnBooksInDescendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -622,7 +706,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "title", SortOrder.Descending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -630,7 +714,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenCalled_ShouldIncludeRelatedEntities() + public async Task GetAllAsync_WhenPaginationIsProvided_ShouldIncludeRelatedEntities() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -647,7 +731,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -667,18 +751,18 @@ public class BookRepositoryTests BookEntity bookWithoutCover = _bookEntityFixture.Create(); bookWithoutCover.LibraryId = libraryId; bookWithoutCover.Path = "/books/a.epub"; - bookWithoutCover.BookArtwork = []; + bookWithoutCover.Artwork = []; BookEntity bookWithEnrichedCover = _bookEntityFixture.Create(); bookWithEnrichedCover.LibraryId = libraryId; bookWithEnrichedCover.Path = "/books/b.epub"; - bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + bookWithEnrichedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; BookEntity bookWithFailedCover = _bookEntityFixture.Create(); bookWithFailedCover.LibraryId = libraryId; bookWithFailedCover.Path = "/books/c.epub"; - bookWithFailedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)]; + bookWithFailedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithFailedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Failed)]; BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); - bookOfAnotherLibrary.BookArtwork = []; + bookOfAnotherLibrary.Artwork = []; _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookWithFailedCover, bookOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -699,13 +783,13 @@ public class BookRepositoryTests Guid libraryId = Guid.NewGuid(); BookEntity bookWithoutCover = _bookEntityFixture.Create(); bookWithoutCover.LibraryId = libraryId; - bookWithoutCover.BookArtwork = []; + bookWithoutCover.Artwork = []; BookEntity bookWithEnrichedCover = _bookEntityFixture.Create(); bookWithEnrichedCover.LibraryId = libraryId; - bookWithEnrichedCover.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + bookWithEnrichedCover.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookWithEnrichedCover.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; BookEntity bookOfAnotherLibrary = _bookEntityFixture.Create(); bookOfAnotherLibrary.LibraryId = Guid.NewGuid(); - bookOfAnotherLibrary.BookArtwork = []; + bookOfAnotherLibrary.Artwork = []; _mockContext.Books.AddRange(bookWithoutCover, bookWithEnrichedCover, bookOfAnotherLibrary); await _mockContext.SaveChangesAsync(); @@ -733,8 +817,8 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); _mockContext.BookContributors.AddRange( - _bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, roleName: "Author", roleCategory: MediaContributorRoleCategory.Author), - _bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator)); + _bookContributorEntityFixture.Create(bookId: firstBook.Id, mediaContributorId: author.Id, role: MediaContributorRole.Author), + _bookContributorEntityFixture.Create(bookId: secondBook.Id, mediaContributorId: translator.Id, role: MediaContributorRole.Translator)); await _mockContext.SaveChangesAsync(); // Act @@ -756,7 +840,7 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.DeleteAsync(book.Id, CancellationToken.None); + Result result = await _sut.DeleteByIdAsync(book.Id, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -770,7 +854,7 @@ public class BookRepositoryTests public async Task DeleteAsync_WhenBookDoesNotExist_ShouldReturnError() { // Act - Result result = await _sut.DeleteAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -786,7 +870,7 @@ public class BookRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(book.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(book.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -797,7 +881,7 @@ public class BookRepositoryTests public async Task GetByIdAsync_WhenBookDoesNotExist_ShouldReturnNull() { // Act - Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -812,12 +896,12 @@ public class BookRepositoryTests book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(book.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(book.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -825,7 +909,7 @@ public class BookRepositoryTests Assert.Equal(2, retrievedBook.Tags.Count); Assert.Equal(2, retrievedBook.Genres.Count); Assert.Equal(2, retrievedBook.ISBNs.Count); - Assert.Single(retrievedBook.BookArtwork); + Assert.Single(retrievedBook.Artwork); } [Fact] @@ -857,7 +941,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder() + public async Task GetAllAsync_WhenSortByLanguageCodeAscending_ShouldReturnBooksInAscendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -874,7 +958,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Ascending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "languageCode", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -882,7 +966,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder() + public async Task GetAllAsync_WhenSortByLanguageCodeDescending_ShouldReturnBooksInDescendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -899,7 +983,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "languageCode", SortOrder.Descending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "languageCode", SortOrder.Descending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -907,7 +991,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder() + public async Task GetAllAsync_WhenSortByFormatAscending_ShouldReturnBooksInAscendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -924,7 +1008,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Ascending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "format", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -932,7 +1016,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder() + public async Task GetAllAsync_WhenSortByFormatDescending_ShouldReturnBooksInDescendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -949,7 +1033,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "format", SortOrder.Descending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "format", SortOrder.Descending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -957,7 +1041,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder() + public async Task GetAllAsync_WhenSortByMetadataProviderAscending_ShouldReturnBooksInAscendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -974,7 +1058,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "metadataProvider", SortOrder.Ascending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -982,7 +1066,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder() + public async Task GetAllAsync_WhenSortByMetadataProviderDescending_ShouldReturnBooksInDescendingOrder() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -999,7 +1083,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, "metadataProvider", SortOrder.Descending, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -1007,7 +1091,7 @@ public class BookRepositoryTests } [Fact] - public async Task GetPaginatedAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix() + public async Task GetAllAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -1022,7 +1106,7 @@ public class BookRepositoryTests LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true); // Act - Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -1030,4 +1114,273 @@ public class BookRepositoryTests Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(book => book.Title)); } + [Fact] + public async Task GetAllLiteAsync_WhenFilterIncludesLibraryId_ShouldReturnPaginatedLiteRows() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List books = _bookEntityFixture.CreateMany(3); + foreach (BookEntity book in books) + book.LibraryId = libraryId; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(1, result.Value.CurrentPage); + Assert.Equal(10, result.Value.PerPage); + Assert.Equal(1, result.Value.NumberOfPages); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() + { + // Arrange + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + BaseFilterDto filter = _baseFilterDtoFixture.Create(); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() + { + // Arrange + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnAllLiteRows() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List books = _bookEntityFixture.CreateMany(3); + foreach (BookEntity book in books) + book.LibraryId = libraryId; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(1, result.Value.CurrentPage); + Assert.Equal(3, result.Value.PerPage); + Assert.Equal(1, result.Value.NumberOfPages); + } + + [Fact] + public async Task GetAllLiteAsync_WhenSearchTermProvided_ShouldReturnOnlyMatchingLiteRows() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity fellowshipBook = _bookEntityFixture.Create(); + fellowshipBook.LibraryId = libraryId; + fellowshipBook.Title = "The Fellowship of the Ring"; + BookEntity towersBook = _bookEntityFixture.Create(); + towersBook.LibraryId = libraryId; + towersBook.Title = "The Two Towers"; + _mockContext.Books.AddRange(fellowshipBook, towersBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship"); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal("The Fellowship of the Ring", row.Title); + Assert.Equal(1, result.Value.Count); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPageSizeSmallerThanBookCount_ShouldReturnCorrectPageMetadata() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List books = _bookEntityFixture.CreateMany(5); + foreach (BookEntity book in books) + book.LibraryId = libraryId; + _mockContext.Books.AddRange(books); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(5, result.Value.Count); + Assert.Equal(3, result.Value.NumberOfPages); + Assert.Equal(2, result.Value.CurrentPage); + Assert.Equal(2, result.Value.PerPage); + Assert.Equal(2, result.Value.Data.Count); + } + + [Fact] + public async Task GetAllLiteAsync_WhenSortByTitleDescending_ShouldReturnLiteRowsInDescendingOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity bookA = _bookEntityFixture.Create(); + bookA.LibraryId = libraryId; + bookA.Title = "Book A"; + BookEntity bookB = _bookEntityFixture.Create(); + bookB.LibraryId = libraryId; + bookB.Title = "Book B"; + _mockContext.Books.AddRange(bookA, bookB); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, "title", SortOrder.Descending, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(["Book B", "Book A"], result.Value.Data.Select(row => row.Title)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenIgnoringTheTitlePrefixForSorting_ShouldSortByTitleStrippedOfItsPrefix() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity beneathBook = _bookEntityFixture.Create(title: "Beneath the Surface", includeMetadata: false); + beneathBook.LibraryId = libraryId; + BookEntity artOfWarBook = _bookEntityFixture.Create(title: "The Art of War", includeMetadata: false); + artOfWarBook.LibraryId = libraryId; + _mockContext.Books.AddRange(beneathBook, artOfWarBook); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, shouldIgnoreThePrefixForAlphaPicker: true); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + // Without stripping the prefix, "The Art of War" would be sorted after "Beneath the Surface", since its sort key would start with "the" instead of "art". + Assert.Equal(["The Art of War", "Beneath the Surface"], result.Value.Data.Select(row => row.Title)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasReReleaseYear_ShouldProjectReReleaseYearAsReleaseYear() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(book.ReReleaseYear, row.ReleaseYear); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasNoReReleaseYear_ShouldProjectOriginalReleaseYearAsReleaseYear() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.ReReleaseYear = null; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(book.OriginalReleaseYear, row.ReleaseYear); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasCoverArtwork_ShouldProjectTheCoverFileName() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")]; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal("cover.jpg", row.CoverPath); + } + + [Fact] + public async Task GetAllLiteAsync_WhenBookHasNoCoverArtwork_ShouldProjectNullCoverPath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(); + book.LibraryId = libraryId; + book.Artwork = []; + _mockContext.Books.Add(book); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + BookLiteRow row = Assert.Single(result.Value.Data); + Assert.Null(row.CoverPath); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecificationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecificationTests.cs new file mode 100644 index 00000000..349b200b --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecificationTests.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; +using Lumina.DataAccess.Core.UoW; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookAlphaFilterSpecificationTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly LuminaDbContext _context; + private readonly BookEntityFixture _bookEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookAlphaFilterSpecificationTests() + { + // the specification translates to the SQLite glob() function, 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(); + } + + [Fact] + public void ToExpression_WhenAlphaKeyIsNull_ShouldMatchEveryBook() + { + // Arrange + List books = SeedBooks(("Alpha", null), ("Beta", null), ("1984", null)); + BookAlphaFilterSpecification specification = new(null, false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression())]; + + // Assert + Assert.Equal(books.Count, result.Count); + } + + [Fact] + public void ToExpression_WhenAlphaKeyIsALowercaseLetter_ShouldMatchOnlyBooksWhoseTitleStartsWithIt() + { + // Arrange + SeedBooks(("Fellowship", null), ("Hobbit", null), ("The Two Towers", null)); + BookAlphaFilterSpecification specification = new("f", false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)]; + + // Assert + Assert.Equal(["Fellowship"], result); + } + + [Fact] + public void ToExpression_WhenAlphaKeyIsAnUppercaseLetter_ShouldMatchBooksWhoseTitleStartsWithItsLowercase() + { + // Arrange + SeedBooks(("Fellowship", null), ("Hobbit", null)); + BookAlphaFilterSpecification specification = new("F", false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)]; + + // Assert + Assert.Equal(["Fellowship"], result); + } + + [Fact] + public void ToExpression_WhenNoTitleStartsWithTheAlphaKey_ShouldNotMatchAnyBook() + { + // Arrange + SeedBooks(("Fellowship", null), ("Hobbit", null)); + BookAlphaFilterSpecification specification = new("z", false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression())]; + + // Assert + Assert.Empty(result); + } + + [Fact] + public void ToExpression_WhenAlphaKeyIsTheNumberKey_ShouldMatchOnlyBooksWhoseTitleStartsWithADigit() + { + // Arrange + SeedBooks(("1984", null), ("Alpha", null), ("Beta", null)); + BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)]; + + // Assert + Assert.Equal(["1984"], result); + } + + [Fact] + public void ToExpression_WhenAlphaKeyIsTheSymbolKey_ShouldMatchOnlyBooksWhoseTitleStartsWithASymbol() + { + // Arrange + SeedBooks(("!Important", null), ("1984", null), ("Alpha", null)); + BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)]; + + // Assert + Assert.Equal(["!Important"], result); + } + + [Fact] + public void ToExpression_WhenTitleIsEmpty_ShouldMatchOnTheOriginalTitle() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(title: string.Empty, originalTitle: "Rendezvous", includeMetadata: false); + _context.Books.Add(book); + _context.SaveChanges(); + BookAlphaFilterSpecification specification = new("r", false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression()).Select(entity => entity.OriginalTitle!)]; + + // Assert + Assert.Equal(["Rendezvous"], result); + } + + [Fact] + public void ToExpression_WhenIgnoringThePrefixAndTitleStartsWithThe_ShouldMatchOnTheStrippedTitle() + { + // Arrange + SeedBooks(("The Art of War", null), ("Beneath the Surface", null)); + BookAlphaFilterSpecification specification = new("a", true); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression()).Select(book => book.Title)]; + + // Assert + Assert.Equal(["The Art of War"], result); + } + + [Fact] + public void ToExpression_WhenNotIgnoringThePrefixAndTitleStartsWithThe_ShouldNotMatchOnTheStrippedTitle() + { + // Arrange + SeedBooks(("The Art of War", null), ("Beneath the Surface", null)); + BookAlphaFilterSpecification specification = new("a", false); + + // Act + List result = [.. _context.Books.Where(specification.ToExpression())]; + + // Assert + Assert.Empty(result); + } + + /// + /// Seeds books with the provided titles. + /// + /// The title and original title pairs of the books to seed. + /// The seeded instances. + private List SeedBooks(params (string Title, string? OriginalTitle)[] books) + { + List entities = []; + foreach ((string title, string? originalTitle) in books) + entities.Add(_bookEntityFixture.Create(title: title, originalTitle: originalTitle, includeMetadata: false)); + _context.Books.AddRange(entities); + _context.SaveChanges(); + return entities; + } + + /// + /// 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/Books/Specifications/BookSearchSpecificationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookSearchSpecificationTests.cs similarity index 83% rename from tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookSearchSpecificationTests.cs rename to tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookSearchSpecificationTests.cs index a2ca276f..c38b5b1c 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookSearchSpecificationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookSearchSpecificationTests.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.DataAccess.Core.Repositories.Books.Specifications; +using Lumina.DataAccess.Core.Repositories.BookLibrary.Specifications; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion -namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications; +namespace Lumina.DataAccess.UnitTests.Core.Repositories.BookLibrary.Specifications; /// /// Contains unit tests for the class. @@ -101,7 +101,7 @@ public class BookSearchSpecificationTests } [Fact] - public void ToExpression_WhenTitleMatchesInDifferentCase_ShouldNotMatchCaseInsensitively() + public void ToExpression_WhenTitleMatchesInDifferentCase_ShouldMatchCaseInsensitively() { // Arrange BookEntity book = _bookEntityFixture.Create(); @@ -113,6 +113,22 @@ public class BookSearchSpecificationTests bool result = specification.IsSatisfiedBy(book); // Assert - Assert.False(result); + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenOriginalTitleMatchesInDifferentCase_ShouldMatchCaseInsensitively() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Title = "A Random Title"; + book.OriginalTitle = "Lord of the Rings: The Fellowship"; + BookSearchSpecification specification = new("FELLOWSHIP"); + + // Act + bool result = specification.IsSatisfiedBy(book); + + // Assert + Assert.True(result); } } 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 0333e942..7c44ef48 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.UoW; @@ -81,7 +83,7 @@ public class LibraryRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(library.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -94,7 +96,7 @@ public class LibraryRepositoryTests public async Task GetByIdAsync_WhenLibraryDoesNotExist_ShouldReturnNull() { // Act - Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -147,12 +149,12 @@ public class LibraryRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal(3, result.Value.Count()); - Assert.Equal(libraries, result.Value); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(libraries, result.Value.Data); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs index bd0ea81a..9fede070 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -83,7 +83,7 @@ public class LibraryScanRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(libraryScan.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(libraryScan.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -95,7 +95,7 @@ public class LibraryScanRepositoryTests public async Task GetByIdAsync_WhenLibraryScanDoesNotExist_ShouldReturnNull() { // Act - Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs new file mode 100644 index 00000000..23b27f7d --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/AlbumRepositoryTests.cs @@ -0,0 +1,740 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +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.MediaContributors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +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.DataAccess.UnitTests.Core.Repositories.MusicLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AlbumRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly ITrackRepository _mockTrackRepository; + private readonly AlbumRepository _sut; + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AlbumRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _mockTrackRepository = Substitute.For(); + _mockTrackRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); + _mockTrackRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); + _mockTrackRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>([])); + _sut = new AlbumRepository(_mockContext, _mockTrackRepository); + } + + [Fact] + public async Task InsertAsync_WhenAlbumDoesNotExist_ShouldAddAlbumToContextAndReturnCreated() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedAlbum = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id); + Assert.NotNull(addedAlbum); + } + + [Fact] + public async Task InsertAsync_WhenAlbumWithTheSameIdAlreadyExists_ShouldReturnAlbumAlreadyExists() + { + // Arrange + AlbumEntity existingAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + _mockContext.Albums.Add(existingAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity album = _albumEntityFixture.Create(id: existingAlbum.Id, includeTracks: false, includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumAlreadyExists, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); // Only the existing album should remain tracked. + } + + [Fact] + public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + album.Tracks = + [ + _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false), + _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false) + ]; + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + // The duplicate within the request is detected before the stored paths are even consulted. + await _mockTrackRepository.DidNotReceive().GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists() + { + // Arrange + _mockTrackRepository.GetExistingPathsAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Result.From>(["/music/queen/bohemian-rhapsody.flac"])); + + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + Assert.Empty(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldAddAlbumToContextAndReturnCreated() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false)]; + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The same physical path is only unique within its library, so another library is allowed to register it. + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id); + } + + [Fact] + public async Task InsertAsync_WhenExistingTagAndGenreNamesAreFound_ShouldReplaceThemWithTheStoredInstancesOnTheAlbumAndItsTracks() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre"); + _mockContext.Set().Add(existingTag); + _mockContext.Set().Add(existingGenre); + await _mockContext.SaveChangesAsync(); + + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewAlbumTag")]; + album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewAlbumGenre")]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewTrackTag")]; + track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewTrackGenre")]; + album.Tracks = [track]; + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedAlbum = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id); + Assert.NotNull(addedAlbum); + AlbumEntity addedAlbumEntity = addedAlbum!.Entity; + Assert.Contains(addedAlbumEntity.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedAlbumEntity.Tags, tag => tag.Name == "NewAlbumTag" && !ReferenceEquals(tag, existingTag)); + Assert.Contains(addedAlbumEntity.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedAlbumEntity.Genres, genre => genre.Name == "NewAlbumGenre" && !ReferenceEquals(genre, existingGenre)); + TrackEntity addedTrack = Assert.Single(addedAlbumEntity.Tracks); + Assert.Contains(addedTrack.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrack.Tags, tag => tag.Name == "NewTrackTag" && !ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrack.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedTrack.Genres, genre => genre.Name == "NewTrackGenre" && !ReferenceEquals(genre, existingGenre)); + // The shared rows are reused instead of being duplicated. + Assert.Single(_mockContext.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldTrackASingleInstancePerName() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: album.LibraryId, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + album.Tracks = [track]; + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The name shared by the album and its tracks is represented by a single tracked instance, so the same key is never tracked twice. + EntityEntry addedTag = Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.Entity.Name == "SharedNewTag"); + EntityEntry addedGenre = Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.Entity.Name == "SharedNewGenre"); + Assert.True(ReferenceEquals(album.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity)); + Assert.True(ReferenceEquals(track.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity)); + Assert.True(ReferenceEquals(album.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity)); + Assert.True(ReferenceEquals(track.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity)); + } + + [Fact] + public async Task InsertAsync_WhenAlbumHasNoTracksOrTagsOrGenres_ShouldStillAddAlbumAndReturnCreated() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + album.Tags = []; + album.Genres = []; + + // Act + Result result = await _sut.InsertAsync(album, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedAlbum = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == album.Id); + Assert.NotNull(addedAlbum); + Assert.Empty(addedAlbum!.Entity.Tracks); + Assert.Empty(addedAlbum.Entity.Tags); + Assert.Empty(addedAlbum.Entity.Genres); + } + + [Fact] + public async Task UpdateAsync_WhenAlbumDoesNotExist_ShouldReturnAlbumNotFound() + { + // Arrange + AlbumEntity data = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenAlbumExists_ShouldUpdateItsScalarProperties() + { + // Arrange + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Title = "A Night at the Opera"; + data.TotalTracks = 12; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + AlbumEntity? retrievedAlbum = await _mockContext.Albums.FindAsync(storedAlbum.Id); + Assert.NotNull(retrievedAlbum); + Assert.Equal("A Night at the Opera", retrievedAlbum!.Title); + Assert.Equal(12, retrievedAlbum.TotalTracks); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingArtistIdAndLibraryIdDiffer_ShouldPreserveTheStoredIdentity() + { + // Arrange + Guid storedArtistId = Guid.NewGuid(); + Guid storedLibraryId = Guid.NewGuid(); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtistId, libraryId: storedLibraryId, includeTracks: false, includeMetadata: false); + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.ArtistId = Guid.NewGuid(); + data.LibraryId = Guid.NewGuid(); + data.Title = "A Night at the Opera"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? retrievedAlbum = await _mockContext.Albums.FindAsync(storedAlbum.Id); + Assert.NotNull(retrievedAlbum); + Assert.Equal(storedArtistId, retrievedAlbum!.ArtistId); + Assert.Equal(storedLibraryId, retrievedAlbum.LibraryId); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingAuditColumnsDiffer_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + storedAlbum.CreatedOnUtc = storedCreatedOnUtc; + storedAlbum.CreatedBy = storedCreatedBy; + storedAlbum.UpdatedOnUtc = null; + storedAlbum.UpdatedBy = null; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Title = "A Night at the Opera"; + data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + data.CreatedBy = Guid.NewGuid(); + data.UpdatedOnUtc = DateTime.UtcNow; + data.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity? retrievedAlbum = await _mockContext.Albums.FindAsync(storedAlbum.Id); + Assert.NotNull(retrievedAlbum); + Assert.Equal("A Night at the Opera", retrievedAlbum!.Title); + // The audit columns are owned by the auditing interceptor alone, so an edit never overwrites them. + Assert.Equal(storedCreatedOnUtc, retrievedAlbum.CreatedOnUtc); + Assert.Equal(storedCreatedBy, retrievedAlbum.CreatedBy); + Assert.Null(retrievedAlbum.UpdatedOnUtc); + Assert.Null(retrievedAlbum.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenRatingsChange_ShouldReplaceTheChangedAddTheNewAndRemoveTheMissingOnes() + { + // Arrange + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + storedAlbum.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20) + ]; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Ratings = + [ + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5) + ]; + + // 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.Ratings).FirstOrDefaultAsync(album => album.Id == storedAlbum.Id); + Assert.NotNull(retrievedAlbum); + List ratings = retrievedAlbum!.Ratings; + Assert.Equal(3, ratings.Count); + // The rating whose value changed is replaced, the unchanged one is kept, the missing one is removed and the new one is added. + Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M); + Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M); + Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M); + Assert.DoesNotContain(ratings, rating => rating.Source == AudioRatingSource.LastFm); + } + + [Fact] + public async Task UpdateAsync_WhenAnUnchangedContributorIsSubmitted_ShouldPreserveItsStoredIdentityAndAuditColumns() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + AlbumContributorEntity keptContributor = _albumContributorEntityFixture.Create( + albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + storedAlbum.Contributors = [keptContributor]; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + DateTime keptContributorCreatedOnUtc = keptContributor.CreatedOnUtc; + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Contributors = + [_albumContributorEntityFixture.Create(albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer)]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + AlbumContributorEntity storedContributor = Assert.Single( + await _mockContext.Set().Where(contributor => contributor.AlbumId == storedAlbum.Id).ToListAsync()); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptContributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenContributorsChange_ShouldDeleteTheRemovedAndInsertTheAddedOnes() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + Guid removedMediaContributorId = Guid.NewGuid(); + Guid addedMediaContributorId = Guid.NewGuid(); + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + AlbumContributorEntity keptContributor = _albumContributorEntityFixture.Create( + albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + AlbumContributorEntity removedContributor = _albumContributorEntityFixture.Create( + albumId: storedAlbum.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer); + storedAlbum.Contributors = [keptContributor, removedContributor]; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Contributors = + [ + _albumContributorEntityFixture.Create(albumId: storedAlbum.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer), + _albumContributorEntityFixture.Create(albumId: storedAlbum.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals) + ]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await _mockContext.Set() + .Where(contributor => contributor.AlbumId == storedAlbum.Id) + .ToListAsync(); + Assert.Equal(2, storedContributors.Count); + // The unchanged participation keeps its identity, while only the delta is deleted and inserted. + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.DoesNotContain(storedContributors, contributor => contributor.MediaContributorId == removedMediaContributorId); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre"); + AlbumEntity storedAlbum = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + storedAlbum.Tags = [existingTag]; + storedAlbum.Genres = [existingGenre]; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + AlbumEntity data = _albumEntityFixture.Create(id: storedAlbum.Id, includeTracks: false, includeMetadata: false); + data.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + data.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + + // 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.Tags) + .Include(album => album.Genres) + .FirstOrDefaultAsync(album => album.Id == storedAlbum.Id); + Assert.NotNull(retrievedAlbum); + TagEntity retrievedTag = Assert.Single(retrievedAlbum!.Tags); + GenreEntity retrievedGenre = Assert.Single(retrievedAlbum.Genres); + Assert.True(ReferenceEquals(retrievedTag, existingTag)); + Assert.True(ReferenceEquals(retrievedGenre, existingGenre)); + // The shared rows are reused instead of being duplicated. + Assert.Single(_mockContext.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task GetByIdAsync_WhenAlbumExists_ShouldReturnTheAlbum() + { + // Arrange + AlbumEntity album = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(album.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByIdAsync_WhenAlbumDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = CreateAlbumWithFullAggregate(artist.Id, libraryId); + _mockContext.Artists.Add(artist); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(album.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity retrievedAlbum = result.Value!; + Assert.NotNull(retrievedAlbum.Artist); + Assert.Equal(artist.Id, retrievedAlbum.Artist!.Id); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Single(retrievedTrack.Ratings); + Assert.Equal(2, retrievedTrack.Tags.Count); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Equal(2, retrievedTrack.Isrcs.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetByArtistIdAsync_WhenCalled_ShouldReturnOnlyTheArtistAlbumsOrderedByTitleThenId() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity betaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Beta", includeTracks: false, includeMetadata: false); + AlbumEntity secondAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false); + AlbumEntity firstAlphaAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Alpha", includeTracks: false, includeMetadata: false); + AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Gamma", includeTracks: false, includeMetadata: false); + _mockContext.Albums.AddRange(betaAlbum, secondAlphaAlbum, firstAlphaAlbum, albumOfAnotherArtist); + await _mockContext.SaveChangesAsync(); + + List artistAlbums = [betaAlbum, secondAlphaAlbum, firstAlphaAlbum]; + Guid[] expectedOrder = [.. artistAlbums.OrderBy(album => album.Title).ThenBy(album => album.Id).Select(album => album.Id)]; + + // Act + Result> result = await _sut.GetByArtistIdAsync(artistId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Select(album => album.Id)); + Assert.DoesNotContain(result.Value, album => album.Id == albumOfAnotherArtist.Id); + } + + [Fact] + public async Task GetByArtistIdAsync_WhenCalled_ShouldIncludeTheRelatedCollections() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = CreateAlbumWithFullAggregate(artist.Id, libraryId); + _mockContext.Artists.Add(artist); + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByArtistIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + AlbumEntity retrievedAlbum = Assert.Single(result.Value); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Single(retrievedTrack.Ratings); + Assert.Equal(2, retrievedTrack.Tags.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistAlbumsOrdered() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity secondAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album B", includeTracks: false, includeMetadata: false); + AlbumEntity firstAlbum = _albumEntityFixture.Create(artistId: artistId, title: "Album A", includeTracks: false, includeMetadata: false); + AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(title: "Album C", includeTracks: false, includeMetadata: false); + _mockContext.Albums.AddRange(secondAlbum, firstAlbum, albumOfAnotherArtist); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(2, page.Count); + Assert.Equal(2, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(2, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + Assert.Equal([firstAlbum.Id, secondAlbum.Id], page.Data.Select(row => row.Id)); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetAlbumsLiteByArtistIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + Guid artistId = Guid.NewGuid(); + List albums = _albumEntityFixture.CreateMany(5); + for (int index = 0; index < albums.Count; index++) + { + albums[index].ArtistId = artistId; + albums[index].Title = $"Album {index}"; + albums[index].Tracks = []; + } + _mockContext.Albums.AddRange(albums); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + + // Act + Result> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + [Fact] + public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldReturnOnlyTheArtistAlbums() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity albumOfArtist = _albumEntityFixture.Create(artistId: artistId, includeTracks: false, includeMetadata: false); + AlbumEntity albumOfAnotherArtist = _albumEntityFixture.Create(includeTracks: false, includeMetadata: false); + _mockContext.Albums.AddRange(albumOfArtist, albumOfAnotherArtist); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + + // Act + Result> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + AlbumLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(albumOfArtist.Id, row.Id); + Assert.Equal(1, result.Value.Count); + } + + [Fact] + public async Task GetAlbumsLiteByArtistIdAsync_WhenCalled_ShouldProjectTheLiteFields() + { + // Arrange + Guid artistId = Guid.NewGuid(); + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false); + album.TotalTracks = 12; + _mockContext.Albums.Add(album); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + + // Act + Result> result = await _sut.GetAlbumsLiteByArtistIdAsync(artistId, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + AlbumLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(album.Id, row.Id); + Assert.Equal("A Night at the Opera", row.Title); + Assert.Equal(12, row.TotalTracks); + } + + /// + /// Creates an album that belongs to the artist identified by , with every related collection populated deterministically. + /// + /// The Id of the artist that owns the album. + /// The Id of the library that owns the album. + /// The created album. + private AlbumEntity CreateAlbumWithFullAggregate(Guid artistId, Guid libraryId) + { + AlbumEntity album = _albumEntityFixture.Create(artistId: artistId, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + album.Tags = [_tagEntityFixture.Create(name: "AlbumTag1"), _tagEntityFixture.Create(name: "AlbumTag2")]; + album.Genres = [_genreEntityFixture.Create(name: "AlbumGenre1"), _genreEntityFixture.Create(name: "AlbumGenre2")]; + album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, includeMetadata: false); + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)]; + track.Tags = [_tagEntityFixture.Create(name: "TrackTag1"), _tagEntityFixture.Create(name: "TrackTag2")]; + track.Genres = [_genreEntityFixture.Create(name: "TrackGenre1"), _genreEntityFixture.Create(name: "TrackGenre2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + album.Tracks = [track]; + return album; + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs new file mode 100644 index 00000000..add56a0c --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/ArtistRepositoryTests.cs @@ -0,0 +1,1146 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Filtering; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +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.MediaContributors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +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 ArtistRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly AlbumRepository _albumRepository; + private readonly TrackRepository _trackRepository; + private readonly ArtistRepository _sut; + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly ArtistContributorEntityFixture _artistContributorEntityFixture = new(); + private readonly AlbumContributorEntityFixture _albumContributorEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new(); + private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ArtistRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _trackRepository = new TrackRepository(_mockContext); + _albumRepository = new AlbumRepository(_mockContext, _trackRepository); + _sut = new ArtistRepository(_mockContext, _albumRepository, _trackRepository); + } + + [Fact] + public async Task InsertAsync_WhenArtistDoesNotExist_ShouldAddArtistToContextAndReturnCreated() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedArtist = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + Assert.NotNull(addedArtist); + } + + [Fact] + public async Task InsertAsync_WhenArtistWithTheSameIdAlreadyExists_ShouldReturnArtistAlreadyExists() + { + // Arrange + ArtistEntity existingArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(existingArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(id: existingArtist.Id, includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAlreadyExists, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); // Only the existing artist should remain tracked. + } + + [Fact] + public async Task InsertAsync_WhenAnotherArtistOfTheSameLibraryHasTheSameName_ShouldReturnArtistAlreadyExists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(existingArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasAnArtistWithTheSameName_ShouldAddArtistToContextAndReturnCreated() + { + // Arrange + ArtistEntity existingArtist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(existingArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: Guid.NewGuid(), name: "Queen", includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // An artist only has to be unique within its own library, so the second library is allowed to register the same name. + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + } + + [Fact] + public async Task InsertAsync_WhenTwoTracksOfTheSameRequestShareAPath_ShouldReturnTrackAlreadyExists() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity firstTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false); + TrackEntity secondTrack = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false); + album.Tracks = [firstTrack, secondTrack]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + // The duplicate within the request is detected before anything is written. + Assert.Empty(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task InsertAsync_WhenATrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: Guid.NewGuid(), libraryId: libraryId, includeTracks: false, includeMetadata: false); + storedAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + _mockContext.Albums.Add(storedAlbum); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: libraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + Assert.Empty(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldAddArtistToContextAndReturnCreated() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + album.Tracks = [_trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, path: "/music/queen/we-will-rock-you.flac", includeMetadata: false)]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The same physical path is only unique within its library, so another library is allowed to register it. + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + } + + [Fact] + public async Task InsertAsync_WhenExistingTagAndGenreNamesAreFound_ShouldReplaceThemWithTheStoredInstancesAcrossAlbumsAndTracks() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre"); + _mockContext.Set().Add(existingTag); + _mockContext.Set().Add(existingGenre); + await _mockContext.SaveChangesAsync(); + + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewAlbumTag")]; + album.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewAlbumGenre")]; + track.Tags = [_tagEntityFixture.Create(name: "ExistingTag"), _tagEntityFixture.Create(name: "NewTrackTag")]; + track.Genres = [_genreEntityFixture.Create(name: "ExistingGenre"), _genreEntityFixture.Create(name: "NewTrackGenre")]; + album.Tracks = [track]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedArtist = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + Assert.NotNull(addedArtist); + AlbumEntity addedAlbum = Assert.Single(addedArtist!.Entity.Albums); + Assert.Contains(addedAlbum.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedAlbum.Tags, tag => tag.Name == "NewAlbumTag" && !ReferenceEquals(tag, existingTag)); + Assert.Contains(addedAlbum.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedAlbum.Genres, genre => genre.Name == "NewAlbumGenre" && !ReferenceEquals(genre, existingGenre)); + TrackEntity addedTrack = Assert.Single(addedAlbum.Tracks); + Assert.Contains(addedTrack.Tags, tag => tag.Name == "ExistingTag" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrack.Tags, tag => tag.Name == "NewTrackTag" && !ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrack.Genres, genre => genre.Name == "ExistingGenre" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedTrack.Genres, genre => genre.Name == "NewTrackGenre" && !ReferenceEquals(genre, existingGenre)); + // The shared rows are reused instead of being duplicated. + Assert.Single(_mockContext.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task InsertAsync_WhenANewTagAndGenreNameIsSharedBetweenTheAlbumAndItsTracks_ShouldTrackASingleInstancePerName() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, includeMetadata: false); + album.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + album.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + track.Tags = [_tagEntityFixture.Create(name: "SharedNewTag")]; + track.Genres = [_genreEntityFixture.Create(name: "SharedNewGenre")]; + album.Tracks = [track]; + artist.Albums = [album]; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The name shared by the album and its tracks is represented by a single tracked instance, so the same key is never tracked twice. + EntityEntry addedTag = Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.Entity.Name == "SharedNewTag"); + EntityEntry addedGenre = Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.Entity.Name == "SharedNewGenre"); + Assert.True(ReferenceEquals(album.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity)); + Assert.True(ReferenceEquals(track.Tags.Single(tag => tag.Name == "SharedNewTag"), addedTag.Entity)); + Assert.True(ReferenceEquals(album.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity)); + Assert.True(ReferenceEquals(track.Genres.Single(genre => genre.Name == "SharedNewGenre"), addedGenre.Entity)); + } + + [Fact] + public async Task InsertAsync_WhenArtistHasNoTagsOrGenres_ShouldStillAddArtistAndReturnCreated() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: true, includeContributors: false, includeMetadata: false); + AlbumEntity album = Assert.Single(artist.Albums); + album.Tags = []; + album.Genres = []; + album.Tracks[0].Tags = []; + album.Tracks[0].Genres = []; + + // Act + Result result = await _sut.InsertAsync(artist, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedArtist = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == artist.Id); + Assert.NotNull(addedArtist); + Assert.Empty(addedArtist!.Entity.Albums[0].Tags); + Assert.Empty(addedArtist.Entity.Albums[0].Genres); + } + + [Fact] + public async Task UpdateAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound() + { + // Arrange + ArtistEntity data = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenArtistExists_ShouldUpdateItsScalarProperties() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Name = "Freddie Mercury"; + data.Website = "https://www.queenonline.com"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + ArtistEntity? retrievedArtist = await _mockContext.Artists.FindAsync(storedArtist.Id); + Assert.NotNull(retrievedArtist); + Assert.Equal("Freddie Mercury", retrievedArtist!.Name); + Assert.Equal("https://www.queenonline.com", retrievedArtist.Website); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingLibraryIdDiffers_ShouldPreserveTheStoredLibraryId() + { + // Arrange + Guid storedLibraryId = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(libraryId: storedLibraryId, includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.LibraryId = Guid.NewGuid(); + data.Name = "Queen"; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? retrievedArtist = await _mockContext.Artists.FindAsync(storedArtist.Id); + Assert.NotNull(retrievedArtist); + Assert.Equal(storedLibraryId, retrievedArtist!.LibraryId); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingAuditColumnsDiffer_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + storedArtist.CreatedOnUtc = storedCreatedOnUtc; + storedArtist.CreatedBy = storedCreatedBy; + storedArtist.UpdatedOnUtc = null; + storedArtist.UpdatedBy = null; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Name = "Freddie"; + data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + data.CreatedBy = Guid.NewGuid(); + data.UpdatedOnUtc = DateTime.UtcNow; + data.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity? retrievedArtist = await _mockContext.Artists.FindAsync(storedArtist.Id); + Assert.NotNull(retrievedArtist); + Assert.Equal("Freddie", retrievedArtist!.Name); + // The audit columns are owned by the auditing interceptor alone, so an edit never overwrites them. + Assert.Equal(storedCreatedOnUtc, retrievedArtist.CreatedOnUtc); + Assert.Equal(storedCreatedBy, retrievedArtist.CreatedBy); + Assert.Null(retrievedArtist.UpdatedOnUtc); + Assert.Null(retrievedArtist.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenAnUnchangedContributorIsSubmitted_ShouldPreserveItsStoredIdentityAndAuditColumns() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + ArtistContributorEntity keptContributor = _artistContributorEntityFixture.Create( + artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + storedArtist.Contributors = [keptContributor]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + DateTime keptContributorCreatedOnUtc = keptContributor.CreatedOnUtc; + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Contributors = + [_artistContributorEntityFixture.Create(artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer)]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + ArtistContributorEntity storedContributor = Assert.Single( + await _mockContext.Set().Where(contributor => contributor.ArtistId == storedArtist.Id).ToListAsync()); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptContributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenContributorsChange_ShouldDeleteTheRemovedAndInsertTheAddedOnes() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + Guid removedMediaContributorId = Guid.NewGuid(); + Guid addedMediaContributorId = Guid.NewGuid(); + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + ArtistContributorEntity keptContributor = _artistContributorEntityFixture.Create( + artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer); + ArtistContributorEntity removedContributor = _artistContributorEntityFixture.Create( + artistId: storedArtist.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Composer); + storedArtist.Contributors = [keptContributor, removedContributor]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Contributors = + [ + _artistContributorEntityFixture.Create(artistId: storedArtist.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Producer), + _artistContributorEntityFixture.Create(artistId: storedArtist.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals) + ]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await _mockContext.Set() + .Where(contributor => contributor.ArtistId == storedArtist.Id) + .ToListAsync(); + Assert.Equal(2, storedContributors.Count); + // The unchanged participation keeps its identity, while only the delta is deleted and inserted. + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.DoesNotContain(storedContributors, contributor => contributor.MediaContributorId == removedMediaContributorId); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenAlbumsChange_ShouldInsertTheAddedUpdateTheExistingAndRemoveTheMissingOnes() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity updatedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + AlbumEntity removedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + storedArtist.Albums = [updatedAlbum, removedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingUpdatedAlbum = _albumEntityFixture.Create(id: updatedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + AlbumEntity incomingAddedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingUpdatedAlbum, incomingAddedAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedAlbums = await _mockContext.Albums.ToListAsync(); + Assert.Contains(storedAlbums, album => album.Id == updatedAlbum.Id); + Assert.Contains(storedAlbums, album => album.Id == incomingAddedAlbum.Id); + Assert.DoesNotContain(storedAlbums, album => album.Id == removedAlbum.Id); + } + + [Fact] + public async Task UpdateAsync_WhenTwoNewTracksOfTheRequestShareAPath_ShouldReturnTrackAlreadyExistsBeforeWriting() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + storedAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false)]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + incomingAlbum.Tracks = + [ + _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false), + _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/duplicate.flac", includeMetadata: false) + ]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + // The unique path is checked for the whole request before any album or track is written. + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + } + + [Fact] + public async Task UpdateAsync_WhenANewTrackPathIsAlreadyStoredInTheLibrary_ShouldReturnTrackAlreadyExistsBeforeWriting() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + storedAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + incomingAlbum.Tracks = [_trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false)]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + Assert.DoesNotContain(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + } + + [Fact] + public async Task UpdateAsync_WhenTracksChangeWithinAnAlbum_ShouldInsertTheAddedUpdateTheExistingAndRemoveTheMissingOnes() + { + // Arrange + ArtistEntity storedArtist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + AlbumEntity storedAlbum = _albumEntityFixture.Create(artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + TrackEntity keptTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + TrackEntity removedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + storedAlbum.Tracks = [keptTrack, removedTrack]; + storedArtist.Albums = [storedAlbum]; + _mockContext.Artists.Add(storedArtist); + await _mockContext.SaveChangesAsync(); + + TrackEntity incomingKeptTrack = _trackEntityFixture.Create(id: keptTrack.Id, albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + incomingKeptTrack.Title = "Somebody to Love"; + TrackEntity incomingAddedTrack = _trackEntityFixture.Create(albumId: storedAlbum.Id, libraryId: storedArtist.LibraryId, includeMetadata: false); + AlbumEntity incomingAlbum = _albumEntityFixture.Create(id: storedAlbum.Id, artistId: storedArtist.Id, libraryId: storedArtist.LibraryId, includeTracks: false, includeMetadata: false); + incomingAlbum.Tracks = [incomingKeptTrack, incomingAddedTrack]; + ArtistEntity data = _artistEntityFixture.Create(id: storedArtist.Id, includeAlbums: false, includeContributors: false); + data.Albums = [incomingAlbum]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedTracks = await _mockContext.Tracks.ToListAsync(); + Assert.Contains(storedTracks, track => track.Id == keptTrack.Id); + Assert.Contains(storedTracks, track => track.Id == incomingAddedTrack.Id); + Assert.DoesNotContain(storedTracks, track => track.Id == removedTrack.Id); + Assert.Equal("Somebody to Love", storedTracks.Single(track => track.Id == keptTrack.Id).Title); + } + + [Fact] + public async Task GetByIdAsync_WhenArtistExists_ShouldReturnTheArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(artist.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByIdAsync_WhenArtistDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections() + { + // Arrange + ArtistEntity artist = CreateArtistWithFullAggregate(); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(artist.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity retrievedArtist = result.Value!; + Assert.Single(retrievedArtist.Contributors); + AlbumEntity retrievedAlbum = Assert.Single(retrievedArtist.Albums); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Single(retrievedTrack.Ratings); + Assert.Equal(2, retrievedTrack.Tags.Count); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Equal(2, retrievedTrack.Isrcs.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task DeleteByIdAsync_WhenArtistExists_ShouldRemoveItAndReturnDeleted() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByIdAsync(artist.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + Assert.Contains(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Deleted && entry.Entity.Id == artist.Id); + await _mockContext.SaveChangesAsync(); + Assert.DoesNotContain(await _mockContext.Artists.ToListAsync(), candidate => candidate.Id == artist.Id); + } + + [Fact] + public async Task DeleteByIdAsync_WhenArtistDoesNotExist_ShouldReturnArtistNotFound() + { + // Act + Result result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNotFound, result.FirstError); + } + + [Fact] + public async Task GetAllAsync_WhenFilterIsNotALibraryFilter_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + BaseFilterDto filter = _baseFilterDtoFixture.Create(); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnOnlyTheArtistsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(firstArtist, secondArtist, artistOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.All(result.Value.Data, artist => Assert.Equal(libraryId, artist.LibraryId)); + Assert.DoesNotContain(result.Value.Data, artist => artist.Id == artistOfAnotherLibrary.Id); + } + + [Theory] + [InlineData("Queens")] // The search term matches the stored casing. + [InlineData("queens")] // The search term is entirely lower case. + [InlineData("QUEENS")] // The search term is entirely upper case. + public async Task GetAllAsync_WhenSearchTermProvided_ShouldMatchTheNameCaseInsensitively(string searchTerm) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity matchingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistEntity otherArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Radiohead", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(matchingArtist, otherArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: searchTerm); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity retrievedArtist = Assert.Single(result.Value.Data); + Assert.Equal(matchingArtist.Id, retrievedArtist.Id); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldOrderByNameThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + ArtistEntity secondAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity firstAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(betaArtist, secondAlphaArtist, firstAlphaArtist); + await _mockContext.SaveChangesAsync(); + + List seededArtists = [betaArtist, secondAlphaArtist, firstAlphaArtist]; + Guid[] expectedOrder = [.. seededArtists.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id).Select(artist => artist.Id)]; + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Data.Select(artist => artist.Id)); + } + + [Fact] + public async Task GetAllAsync_WhenSortOrderIsDescending_ShouldOrderByNameDescendingThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(alphaArtist, betaArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, SortOrder.Descending, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([betaArtist.Id, alphaArtist.Id], result.Value.Data.Select(artist => artist.Id)); + } + + [Theory] + [InlineData("website", SortOrder.Ascending)] // the website field, ascending + [InlineData("website", SortOrder.Descending)] // the website field, descending + [InlineData("musicbrainzartistid", SortOrder.Ascending)] // the MusicBrainz artist Id field, ascending + [InlineData("musicbrainzartistid", SortOrder.Descending)] // the MusicBrainz artist Id field, descending + [InlineData("createdonutc", SortOrder.Ascending)] // the creation timestamp field, ascending + [InlineData("createdonutc", SortOrder.Descending)] // the creation timestamp field, descending + [InlineData("updatedonutc", SortOrder.Ascending)] // the update timestamp field, ascending + [InlineData("updatedonutc", SortOrder.Descending)] // the update timestamp field, descending + public async Task GetAllAsync_WhenSortedByField_ShouldOrderByFieldThenById(string sortBy, SortOrder sortOrder) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Second", includeAlbums: false, includeContributors: false); + ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "First", includeAlbums: false, includeContributors: false); + // The two seeded artists carry a smaller value for every sortable field, so each sort key has a deterministic expected order. + firstArtist.Website = "https://a.example.com"; + secondArtist.Website = "https://b.example.com"; + firstArtist.MusicBrainzArtistId = Guid.Parse("00000000-0000-0000-0000-000000000001"); + secondArtist.MusicBrainzArtistId = Guid.Parse("00000000-0000-0000-0000-000000000002"); + firstArtist.CreatedOnUtc = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + secondArtist.CreatedOnUtc = new DateTime(2024, 1, 2, 0, 0, 0, DateTimeKind.Utc); + firstArtist.UpdatedOnUtc = new DateTime(2024, 2, 1, 0, 0, 0, DateTimeKind.Utc); + secondArtist.UpdatedOnUtc = new DateTime(2024, 2, 2, 0, 0, 0, DateTimeKind.Utc); + _mockContext.Artists.AddRange(secondArtist, firstArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, sortBy, sortOrder, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Guid[] expectedOrder = sortOrder == SortOrder.Descending + ? [secondArtist.Id, firstArtist.Id] + : [firstArtist.Id, secondArtist.Id]; + Assert.Equal(expectedOrder, result.Value.Data.Select(artist => artist.Id)); + } + + [Fact] + public async Task GetAllAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistsWithExpectedMetadata() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(3); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(3, page.Count); + Assert.Equal(3, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(3, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetAllAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(5); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + [Fact] + public async Task GetAllAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections() + { + // Arrange + ArtistEntity artist = CreateArtistWithFullAggregate(); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: artist.LibraryId); + + // Act + Result> result = await _sut.GetAllAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistEntity retrievedArtist = Assert.Single(result.Value.Data); + Assert.Single(retrievedArtist.Contributors); + AlbumEntity retrievedAlbum = Assert.Single(retrievedArtist.Albums); + Assert.Single(retrievedAlbum.Ratings); + Assert.Equal(2, retrievedAlbum.Tags.Count); + Assert.Equal(2, retrievedAlbum.Genres.Count); + Assert.Single(retrievedAlbum.Contributors); + TrackEntity retrievedTrack = Assert.Single(retrievedAlbum.Tracks); + Assert.Single(retrievedTrack.Ratings); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterIsNotALibraryFilter_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + BaseFilterDto filter = _baseFilterDtoFixture.Create(); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnFilterMustIncludeLibraryId() + { + // Arrange + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.FilterMustIncludeLibraryId, result.FirstError); + } + + [Fact] + public async Task GetAllLiteAsync_WhenCalled_ShouldReturnOnlyTheArtistsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artistOfLibrary = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false); + ArtistEntity artistOfAnotherLibrary = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(artistOfLibrary, artistOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(artistOfLibrary.Id, row.Id); + Assert.Equal(1, result.Value.Count); + } + + [Theory] + [InlineData("Queens")] // The search term matches the stored casing. + [InlineData("queens")] // The search term is entirely lower case. + [InlineData("QUEENS")] // The search term is entirely upper case. + public async Task GetAllLiteAsync_WhenSearchTermProvided_ShouldMatchTheNameCaseInsensitively(string searchTerm) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity matchingArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistEntity otherArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Radiohead", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(matchingArtist, otherArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: searchTerm); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(matchingArtist.Id, row.Id); + } + + [Fact] + public async Task GetAllLiteAsync_WhenCalled_ShouldOrderByNameThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + ArtistEntity secondAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity firstAlphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(betaArtist, secondAlphaArtist, firstAlphaArtist); + await _mockContext.SaveChangesAsync(); + + List seededArtists = [betaArtist, secondAlphaArtist, firstAlphaArtist]; + Guid[] expectedOrder = [.. seededArtists.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id).Select(artist => artist.Id)]; + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Data.Select(row => row.Id)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenSortOrderIsDescending_ShouldOrderByNameDescendingThenById() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha", includeAlbums: false, includeContributors: false); + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta", includeAlbums: false, includeContributors: false); + _mockContext.Artists.AddRange(alphaArtist, betaArtist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, SortOrder.Descending, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([betaArtist.Id, alphaArtist.Id], result.Value.Data.Select(artist => artist.Id)); + } + + [Fact] + public async Task GetAllLiteAsync_WhenCalled_ShouldProjectOnlyTheIdAndTheName() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: "Queen", includeAlbums: false, includeContributors: false); + _mockContext.Artists.Add(artist); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + ArtistLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(artist.Id, row.Id); + Assert.Equal("Queen", row.Name); + } + + [Fact] + public async Task GetAllLiteAsync_WhenPaginationDataIsNull_ShouldReturnAllArtistsWithExpectedMetadata() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(3); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(null, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(3, page.Count); + Assert.Equal(3, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(3, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetAllLiteAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List artists = _artistEntityFixture.CreateMany(5); + foreach (ArtistEntity artist in artists) + artist.LibraryId = libraryId; + _mockContext.Artists.AddRange(artists); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); + + // Act + Result> result = await _sut.GetAllLiteAsync(paginationData, null, null, filter, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + /// + /// Creates an artist that owns an album which in turn owns a track, with every related collection of the aggregate populated deterministically. + /// + /// The created artist. + private ArtistEntity CreateArtistWithFullAggregate() + { + ArtistEntity artist = _artistEntityFixture.Create(includeAlbums: false, includeContributors: false); + artist.Contributors = + [_artistContributorEntityFixture.Create(artistId: artist.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + AlbumEntity album = _albumEntityFixture.Create(artistId: artist.Id, libraryId: artist.LibraryId, includeTracks: false, includeMetadata: false); + album.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + album.Tags = [_tagEntityFixture.Create(name: "AlbumTag1"), _tagEntityFixture.Create(name: "AlbumTag2")]; + album.Genres = [_genreEntityFixture.Create(name: "AlbumGenre1"), _genreEntityFixture.Create(name: "AlbumGenre2")]; + album.Contributors = [_albumContributorEntityFixture.Create(albumId: album.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Producer)]; + TrackEntity track = _trackEntityFixture.Create(albumId: album.Id, libraryId: artist.LibraryId, includeMetadata: false); + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.User, voteCount: 10)]; + track.Tags = [_tagEntityFixture.Create(name: "TrackTag1"), _tagEntityFixture.Create(name: "TrackTag2")]; + track.Genres = [_genreEntityFixture.Create(name: "TrackGenre1"), _genreEntityFixture.Create(name: "TrackGenre2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + album.Tracks = [track]; + artist.Albums = [album]; + return artist; + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecificationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecificationTests.cs new file mode 100644 index 00000000..cd3ddb0d --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/Specifications/ArtistSearchSpecificationTests.cs @@ -0,0 +1,111 @@ +#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.Specifications; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.MusicLibrary.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistSearchSpecificationTests +{ + private readonly ArtistEntityFixture _artistEntityFixture = new(); + + [Fact] + public void ToExpression_WhenNameContainsSearchTerm_ShouldMatchArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new("Stone"); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenNameDoesNotContainSearchTerm_ShouldNotMatchArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new("Queen"); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToExpression_WhenNameMatchesInDifferentCase_ShouldMatchCaseInsensitively() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new("QUEENS"); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenSearchTermIsEmpty_ShouldMatchEveryArtist() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new(string.Empty); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + // The repository guards blank terms with IsNullOrWhiteSpace before building the specification, so an empty term is documented as matching every artist rather than being treated as a literal. + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenSearchTermIsWhitespace_ShouldNotMatchAnArtistWithoutThatWhitespace() + { + // Arrange + ArtistEntity artist = _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false); + ArtistSearchSpecification specification = new(" "); + + // Act + bool result = specification.IsSatisfiedBy(artist); + + // Assert + // A whitespace-only term is not silently ignored, it is matched literally. + Assert.False(result); + } + + [Fact] + public void ToExpression_WhenApplied_ShouldFilterOutNonMatchingArtists() + { + // Arrange + List artists = + [ + _artistEntityFixture.Create(name: "Queens of the Stone Age", includeAlbums: false, includeContributors: false), + _artistEntityFixture.Create(name: "Radiohead", includeAlbums: false, includeContributors: false), + _artistEntityFixture.Create(name: "Stone Temple Pilots", includeAlbums: false, includeContributors: false) + ]; + ArtistSearchSpecification specification = new("stone"); + + // Act + IEnumerable matchingArtists = artists.AsQueryable().Where(specification.ToExpression()); + + // Assert + Assert.Equal(2, matchingArtists.Count()); + Assert.DoesNotContain(matchingArtists, artist => artist.Name == "Radiohead"); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs new file mode 100644 index 00000000..7b12913e --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs @@ -0,0 +1,795 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.DataAccess.Core.Repositories.MusicLibrary; +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.MediaContributors; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +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 TrackRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly TrackRepository _sut; + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly TrackMoodEntityFixture _trackMoodEntityFixture = new(); + private readonly TrackIsrcEntityFixture _trackIsrcEntityFixture = new(); + private readonly TrackContributorEntityFixture _trackContributorEntityFixture = new(); + private readonly AudioRatingEntityFixture _audioRatingEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public TrackRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new TrackRepository(_mockContext); + } + + [Fact] + public async Task InsertAsync_WhenTrackDoesNotExist_ShouldAddTrackToContextAndReturnCreated() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedTrack = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id); + Assert.NotNull(addedTrack); + } + + [Fact] + public async Task InsertAsync_WhenTrackWithTheSameIdAlreadyExists_ShouldReturnTrackAlreadyExists() + { + // Arrange + TrackEntity existingTrack = _trackEntityFixture.Create(includeMetadata: false); + _mockContext.Tracks.Add(existingTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(id: existingTrack.Id, includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); // Only the existing track should remain tracked. + } + + [Fact] + public async Task InsertAsync_WhenAnotherTrackOfTheSameLibraryHasTheSamePath_ShouldReturnTrackAlreadyExists() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity existingTrack = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + _mockContext.Tracks.Add(existingTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackAlreadyExists, result.FirstError); + } + + [Fact] + public async Task InsertAsync_WhenAnotherLibraryHasATrackWithTheSamePath_ShouldAddTrackToContextAndReturnCreated() + { + // Arrange + TrackEntity existingTrack = _trackEntityFixture.Create(path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + _mockContext.Tracks.Add(existingTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/music/queen/bohemian-rhapsody.flac", includeMetadata: false); + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + // The same physical path is only unique within its library, so the second library is allowed to register it. + Assert.Single(_mockContext.ChangeTracker.Entries(), entry => entry.State == EntityState.Added); + } + + [Fact] + public async Task InsertAsync_WhenExistingTagsAreFoundByName_ShouldReplaceThemWithTheStoredInstances() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "Existing"); + _mockContext.Set().Add(existingTag); + await _mockContext.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "Existing"), _tagEntityFixture.Create(name: "New")]; + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedTrack = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id); + Assert.NotNull(addedTrack); + TrackEntity addedTrackEntity = addedTrack!.Entity; + Assert.Equal(2, addedTrackEntity.Tags.Count); + Assert.Contains(addedTrackEntity.Tags, tag => tag.Name == "Existing" && ReferenceEquals(tag, existingTag)); + Assert.Contains(addedTrackEntity.Tags, tag => tag.Name == "New" && !ReferenceEquals(tag, existingTag)); + } + + [Fact] + public async Task InsertAsync_WhenExistingGenresAreFoundByName_ShouldReplaceThemWithTheStoredInstances() + { + // Arrange + GenreEntity existingGenre = _genreEntityFixture.Create(name: "Existing"); + _mockContext.Set().Add(existingGenre); + await _mockContext.SaveChangesAsync(); + + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + track.Genres = [_genreEntityFixture.Create(name: "Existing"), _genreEntityFixture.Create(name: "New")]; + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedTrack = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id); + Assert.NotNull(addedTrack); + TrackEntity addedTrackEntity = addedTrack!.Entity; + Assert.Equal(2, addedTrackEntity.Genres.Count); + Assert.Contains(addedTrackEntity.Genres, genre => genre.Name == "Existing" && ReferenceEquals(genre, existingGenre)); + Assert.Contains(addedTrackEntity.Genres, genre => genre.Name == "New" && !ReferenceEquals(genre, existingGenre)); + } + + [Fact] + public async Task InsertAsync_WhenTrackHasNoTagsOrGenres_ShouldStillAddTrackAndReturnCreated() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + track.Tags = []; + track.Genres = []; + + // Act + Result result = await _sut.InsertAsync(track, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedTrack = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entry => entry.State == EntityState.Added && entry.Entity.Id == track.Id); + Assert.NotNull(addedTrack); + Assert.Empty(addedTrack!.Entity.Tags); + Assert.Empty(addedTrack.Entity.Genres); + } + + [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_ShouldReturnOnlyThePathsUsedByTracksOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity trackOfLibrary = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false); + TrackEntity trackOfAnotherLibrary = _trackEntityFixture.Create(libraryId: Guid.NewGuid(), path: "/music/queen/we-will-rock-you.flac", includeMetadata: false); + _mockContext.Tracks.AddRange(trackOfLibrary, trackOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/love-of-my-life.flac", "/music/queen/we-will-rock-you.flac"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + string existingPath = Assert.Single(result.Value); + Assert.Equal("/music/queen/love-of-my-life.flac", existingPath); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenInputContainsDuplicatePaths_ShouldDeDuplicateTheResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/music/queen/love-of-my-life.flac", includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/love-of-my-life.flac", "/music/queen/love-of-my-life.flac", "/music/queen/love-of-my-life.flac"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + Assert.Equal("/music/queen/love-of-my-life.flac", result.Value.First()); + } + + [Fact] + public async Task GetExistingPathsAsync_WhenPathDiffersOnlyByCase_ShouldNotReportItAsExisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(libraryId: libraryId, path: "/Music/Queen/Love-Of-My-Life.flac", includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetExistingPathsAsync(libraryId, ["/music/queen/love-of-my-life.flac"], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task UpdateAsync_WhenTrackExists_ShouldUpdateItsScalarProperties() + { + // Arrange + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Title = "Somebody to Love"; + data.TrackNumber = 7; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + TrackEntity? retrievedTrack = await _mockContext.Tracks.FindAsync(storedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.Equal("Somebody to Love", retrievedTrack!.Title); + Assert.Equal(7, retrievedTrack.TrackNumber); + } + + [Fact] + public async Task UpdateAsync_WhenTrackDoesNotExist_ShouldReturnTrackNotFound() + { + // Arrange + TrackEntity data = _trackEntityFixture.Create(includeMetadata: false); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingIdentityColumnsDiffer_ShouldPreserveTheStoredIdentity() + { + // Arrange + Guid storedAlbumId = Guid.NewGuid(); + Guid storedLibraryId = Guid.NewGuid(); + TrackEntity storedTrack = _trackEntityFixture.Create(albumId: storedAlbumId, libraryId: storedLibraryId, includeMetadata: false); + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.AlbumId = Guid.NewGuid(); + data.LibraryId = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? retrievedTrack = await _mockContext.Tracks.FindAsync(storedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.Equal(storedAlbumId, retrievedTrack!.AlbumId); + Assert.Equal(storedLibraryId, retrievedTrack.LibraryId); + } + + [Fact] + public async Task UpdateAsync_WhenIncomingAuditColumnsDiffer_ShouldPreserveTheStoredAuditColumns() + { + // Arrange + DateTime storedCreatedOnUtc = new(2020, 3, 4, 5, 6, 7, DateTimeKind.Utc); + Guid storedCreatedBy = Guid.NewGuid(); + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + storedTrack.CreatedOnUtc = storedCreatedOnUtc; + storedTrack.CreatedBy = storedCreatedBy; + storedTrack.UpdatedOnUtc = null; + storedTrack.UpdatedBy = null; + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Title = "Don't Stop Me Now"; + data.CreatedOnUtc = DateTime.UtcNow.AddYears(-10); + data.CreatedBy = Guid.NewGuid(); + data.UpdatedOnUtc = DateTime.UtcNow; + data.UpdatedBy = Guid.NewGuid(); + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? retrievedTrack = await _mockContext.Tracks.FindAsync(storedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.Equal("Don't Stop Me Now", retrievedTrack!.Title); + // The audit columns are owned by the auditing interceptor alone, so an edit never overwrites them. + Assert.Equal(storedCreatedOnUtc, retrievedTrack.CreatedOnUtc); + Assert.Equal(storedCreatedBy, retrievedTrack.CreatedBy); + Assert.Null(retrievedTrack.UpdatedOnUtc); + Assert.Null(retrievedTrack.UpdatedBy); + } + + [Fact] + public async Task UpdateAsync_WhenAnUnchangedContributorIsSubmitted_ShouldPreserveItsStoredIdentityAndAuditColumns() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create( + trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer); + storedTrack.Contributors = [keptContributor]; + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + DateTime keptContributorCreatedOnUtc = keptContributor.CreatedOnUtc; + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Contributors = + [_trackContributorEntityFixture.Create(trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer)]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackContributorEntity storedContributor = Assert.Single( + await _mockContext.Set().Where(contributor => contributor.TrackId == storedTrack.Id).ToListAsync()); + Assert.Equal(keptContributorId, storedContributor.Id); + Assert.Equal(keptContributorCreatedOnUtc, storedContributor.CreatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenContributorsChange_ShouldDeleteTheRemovedAndInsertTheAddedOnes() + { + // Arrange + Guid keptMediaContributorId = Guid.NewGuid(); + Guid removedMediaContributorId = Guid.NewGuid(); + Guid addedMediaContributorId = Guid.NewGuid(); + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + TrackContributorEntity keptContributor = _trackContributorEntityFixture.Create( + trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer); + TrackContributorEntity removedContributor = _trackContributorEntityFixture.Create( + trackId: storedTrack.Id, mediaContributorId: removedMediaContributorId, role: MediaContributorRole.Producer); + storedTrack.Contributors = [keptContributor, removedContributor]; + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + Guid keptContributorId = keptContributor.Id; + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Contributors = + [ + _trackContributorEntityFixture.Create(trackId: storedTrack.Id, mediaContributorId: keptMediaContributorId, role: MediaContributorRole.Composer), + _trackContributorEntityFixture.Create(trackId: storedTrack.Id, mediaContributorId: addedMediaContributorId, role: MediaContributorRole.Vocals) + ]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + List storedContributors = await _mockContext.Set() + .Where(contributor => contributor.TrackId == storedTrack.Id) + .ToListAsync(); + Assert.Equal(2, storedContributors.Count); + // The unchanged participation keeps its identity, while only the delta is deleted and inserted. + Assert.Equal(keptContributorId, storedContributors.Single(contributor => contributor.MediaContributorId == keptMediaContributorId).Id); + Assert.DoesNotContain(storedContributors, contributor => contributor.MediaContributorId == removedMediaContributorId); + Assert.Contains(storedContributors, contributor => contributor.MediaContributorId == addedMediaContributorId); + } + + [Fact] + public async Task UpdateAsync_WhenRatingsChange_ShouldReplaceTheChangedAddTheNewAndRemoveTheMissingOnes() + { + // Arrange + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + storedTrack.Ratings = + [ + _audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 2, maxValue: 5, source: AudioRatingSource.LastFm, voteCount: 20) + ]; + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Ratings = + [ + _audioRatingEntityFixture.Create(value: 3, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100), + _audioRatingEntityFixture.Create(value: 5, maxValue: 5, source: AudioRatingSource.User, voteCount: 10), + _audioRatingEntityFixture.Create(value: 1, maxValue: 5, source: AudioRatingSource.Discogs, voteCount: 5) + ]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? retrievedTrack = await _mockContext.Tracks.Include(track => track.Ratings).FirstOrDefaultAsync(track => track.Id == storedTrack.Id); + Assert.NotNull(retrievedTrack); + List ratings = retrievedTrack!.Ratings; + Assert.Equal(3, ratings.Count); + // The rating whose value changed is replaced, the unchanged one is kept, the missing one is removed and the new one is added. + Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.MusicBrainz && rating.Value == 3M); + Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.User && rating.Value == 5M); + Assert.Contains(ratings, rating => rating.Source == AudioRatingSource.Discogs && rating.Value == 1M); + Assert.DoesNotContain(ratings, rating => rating.Source == AudioRatingSource.LastFm); + } + + [Fact] + public async Task UpdateAsync_WhenTagsAndGenresAlreadyExistByName_ShouldReuseTheStoredRows() + { + // Arrange + TagEntity existingTag = _tagEntityFixture.Create(name: "ExistingTag"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "ExistingGenre"); + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + storedTrack.Tags = [existingTag]; + storedTrack.Genres = [existingGenre]; + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Tags = [_tagEntityFixture.Create(name: "ExistingTag")]; + data.Genres = [_genreEntityFixture.Create(name: "ExistingGenre")]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? retrievedTrack = await _mockContext.Tracks + .Include(track => track.Tags) + .Include(track => track.Genres) + .FirstOrDefaultAsync(track => track.Id == storedTrack.Id); + Assert.NotNull(retrievedTrack); + TagEntity retrievedTag = Assert.Single(retrievedTrack!.Tags); + GenreEntity retrievedGenre = Assert.Single(retrievedTrack.Genres); + Assert.True(ReferenceEquals(retrievedTag, existingTag)); + Assert.True(ReferenceEquals(retrievedGenre, existingGenre)); + // The shared rows are reused instead of being duplicated. + Assert.Single(_mockContext.Set().Where(tag => tag.Name == "ExistingTag")); + Assert.Single(_mockContext.Set().Where(genre => genre.Name == "ExistingGenre")); + } + + [Fact] + public async Task UpdateAsync_WhenMoodsAndIsrcsAreUnchanged_ShouldNotDuplicateThem() + { + // Arrange + TrackEntity storedTrack = _trackEntityFixture.Create(includeMetadata: false); + storedTrack.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Energetic")]; + storedTrack.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + _mockContext.Tracks.Add(storedTrack); + await _mockContext.SaveChangesAsync(); + + TrackEntity data = _trackEntityFixture.Create(id: storedTrack.Id, includeMetadata: false); + data.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + data.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000002")]; + + // Act + Result result = await _sut.UpdateAsync(data, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + TrackEntity? retrievedTrack = await _mockContext.Tracks + .Include(track => track.Moods) + .Include(track => track.Isrcs) + .FirstOrDefaultAsync(track => track.Id == storedTrack.Id); + Assert.NotNull(retrievedTrack); + Assert.Equal(2, retrievedTrack!.Moods.Count); + Assert.Single(retrievedTrack.Moods, mood => mood.Name == "Calm"); + Assert.Contains(retrievedTrack.Moods, mood => mood.Name == "Upbeat"); + Assert.Equal(2, retrievedTrack.Isrcs.Count); + Assert.Single(retrievedTrack.Isrcs, isrc => isrc.Value == "USRC12345678"); + Assert.Contains(retrievedTrack.Isrcs, isrc => isrc.Value == "GBAYE0000002"); + } + + [Fact] + public async Task GetByIdAsync_WhenTrackExists_ShouldReturnTheTrack() + { + // Arrange + TrackEntity track = _trackEntityFixture.Create(includeMetadata: false); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(track.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByIdAsync_WhenTrackDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetByIdAsync_WhenNavigationPropertiesAreIncluded_ShouldPopulateTheRelatedCollections() + { + // 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); + track.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + track.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm"), _trackMoodEntityFixture.Create(name: "Upbeat")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678"), _trackIsrcEntityFixture.Create(value: "GBAYE0000001")]; + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + _mockContext.Artists.Add(artist); + _mockContext.Albums.Add(album); + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(track.Id, cancellationToken: CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + TrackEntity retrievedTrack = result.Value!; + Assert.NotNull(retrievedTrack.Album); + Assert.NotNull(retrievedTrack.Album!.Artist); + Assert.Equal(2, retrievedTrack.Tags.Count); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Equal(2, retrievedTrack.Moods.Count); + Assert.Equal(2, retrievedTrack.Isrcs.Count); + Assert.Single(retrievedTrack.Ratings); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenCalled_ShouldReturnOnlyTheAlbumTracksOrderedByDiscThenTrackThenId() + { + // Arrange + Guid albumId = Guid.NewGuid(); + TrackEntity secondDiscTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/dont-stop-me-now.flac", trackNumber: 1, includeMetadata: false); + secondDiscTrack.DiscNumber = 2; + TrackEntity firstDiscSecondTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/somebody-to-love.flac", trackNumber: 2, includeMetadata: false); + firstDiscSecondTrack.DiscNumber = 1; + TrackEntity firstDiscFirstTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/killer-queen.flac", trackNumber: 1, includeMetadata: false); + firstDiscFirstTrack.DiscNumber = 1; + TrackEntity firstDiscFirstTieTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/seven-seas-of-rhye.flac", trackNumber: 1, includeMetadata: false); + firstDiscFirstTieTrack.DiscNumber = 1; + TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/under-pressure.flac", includeMetadata: false); + _mockContext.Tracks.AddRange(secondDiscTrack, firstDiscSecondTrack, firstDiscFirstTrack, firstDiscFirstTieTrack, trackOfAnotherAlbum); + await _mockContext.SaveChangesAsync(); + + List albumTracks = [firstDiscFirstTrack, firstDiscFirstTieTrack, firstDiscSecondTrack, secondDiscTrack]; + Guid[] expectedOrder = [.. albumTracks + .OrderBy(track => track.DiscNumber) + .ThenBy(track => track.TrackNumber) + .ThenBy(track => track.Id) + .Select(track => track.Id)]; + + // Act + Result> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedOrder, result.Value.Select(track => track.Id)); + Assert.DoesNotContain(result.Value, track => track.Id == trackOfAnotherAlbum.Id); + } + + [Fact] + public async Task GetByAlbumIdAsync_WhenCalled_ShouldIncludeTheRelatedCollections() + { + // Arrange + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/radio-ga-ga.flac", includeMetadata: false); + track.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + track.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + track.Moods = [_trackMoodEntityFixture.Create(name: "Calm")]; + track.Isrcs = [_trackIsrcEntityFixture.Create(value: "USRC12345678")]; + track.Ratings = [_audioRatingEntityFixture.Create(value: 4, maxValue: 5, source: AudioRatingSource.MusicBrainz, voteCount: 100)]; + track.Contributors = [_trackContributorEntityFixture.Create(trackId: track.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Vocals)]; + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByAlbumIdAsync(albumId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + TrackEntity retrievedTrack = Assert.Single(result.Value); + Assert.Equal(2, retrievedTrack.Tags.Count); + Assert.Equal(2, retrievedTrack.Genres.Count); + Assert.Single(retrievedTrack.Moods); + Assert.Single(retrievedTrack.Isrcs); + Assert.Single(retrievedTrack.Ratings); + Assert.Single(retrievedTrack.Contributors); + } + + [Fact] + public async Task GetTracksLiteByAlbumIdAsync_WhenPaginationDataIsNull_ShouldReturnAllTracksOfTheAlbumOrdered() + { + // Arrange + Guid albumId = Guid.NewGuid(); + TrackEntity secondTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/we-are-the-champions.flac", trackNumber: 2, title: "We Are the Champions", includeMetadata: false); + secondTrack.DiscNumber = 1; + TrackEntity firstTrack = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/i-want-to-break-free.flac", trackNumber: 1, title: "Bohemian Rhapsody", includeMetadata: false); + firstTrack.DiscNumber = 1; + TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/a-kind-of-magic.flac", includeMetadata: false); + _mockContext.Tracks.AddRange(secondTrack, firstTrack, trackOfAnotherAlbum); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, null, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(2, page.Count); + Assert.Equal(2, page.Data.Count); + Assert.Equal(1, page.CurrentPage); + Assert.Equal(2, page.PerPage); + Assert.Equal(1, page.NumberOfPages); + Assert.Equal([firstTrack.Id, secondTrack.Id], page.Data.Select(row => row.Id)); + } + + [Theory] + [InlineData(1, 2, 1, 2)] // The first page is fully returned. + [InlineData(2, 2, 2, 2)] // A middle page is fully returned. + [InlineData(3, 2, 3, 1)] // The last page is partially returned. + [InlineData(99, 2, 3, 1)] // A page beyond the last one is clamped to the last page. + public async Task GetTracksLiteByAlbumIdAsync_WhenPaginationIsProvided_ShouldReturnTheRequestedPage(int requestedPage, int perPage, int expectedCurrentPage, int expectedRowCount) + { + // Arrange + Guid albumId = Guid.NewGuid(); + List tracks = _trackEntityFixture.CreateMany(5); + for (int index = 0; index < tracks.Count; index++) + { + tracks[index].AlbumId = albumId; + tracks[index].DiscNumber = 1; + tracks[index].TrackNumber = index + 1; + tracks[index].Path = $"/music/queen/track-{index}.flac"; + tracks[index].Tags = []; + tracks[index].Genres = []; + tracks[index].Moods = []; + tracks[index].Isrcs = []; + tracks[index].Contributors = []; + tracks[index].Ratings = []; + } + _mockContext.Tracks.AddRange(tracks); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: requestedPage, perPage: perPage); + + // Act + Result> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PaginatedResultDto page = result.Value; + Assert.Equal(5, page.Count); + Assert.Equal(3, page.NumberOfPages); + Assert.Equal(expectedCurrentPage, page.CurrentPage); + Assert.Equal(perPage, page.PerPage); + Assert.Equal(expectedRowCount, page.Data.Count); + } + + [Fact] + public async Task GetTracksLiteByAlbumIdAsync_WhenCalled_ShouldReturnOnlyTheTracksOfTheRequestedAlbum() + { + // Arrange + Guid albumId = Guid.NewGuid(); + TrackEntity trackOfAlbum = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/youre-my-best-friend.flac", includeMetadata: false); + TrackEntity trackOfAnotherAlbum = _trackEntityFixture.Create(path: "/music/queen/fat-bottomed-girls.flac", includeMetadata: false); + _mockContext.Tracks.AddRange(trackOfAlbum, trackOfAnotherAlbum); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + + // Act + Result> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + TrackLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(trackOfAlbum.Id, row.Id); + Assert.Equal(1, result.Value.Count); + } + + [Fact] + public async Task GetTracksLiteByAlbumIdAsync_WhenCalled_ShouldProjectTheLiteFields() + { + // Arrange + Guid albumId = Guid.NewGuid(); + TrackEntity track = _trackEntityFixture.Create(albumId: albumId, path: "/music/queen/bicycle-race.flac", title: "Killer Queen", trackNumber: 9, includeMetadata: false); + track.DiscNumber = 3; + _mockContext.Tracks.Add(track); + await _mockContext.SaveChangesAsync(); + + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + + // Act + Result> result = await _sut.GetTracksLiteByAlbumIdAsync(albumId, paginationData, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + TrackLiteRow row = Assert.Single(result.Value.Data); + Assert.Equal(track.Id, row.Id); + Assert.Equal("Killer Queen", row.Title); + Assert.Equal(9, row.TrackNumber); + Assert.Equal(3, row.DiscNumber); + } +} 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 32264bd7..41d5cf96 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/PluginRepositoryTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.UoW; @@ -46,7 +48,7 @@ public class PluginRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(plugin.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(plugin.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -130,26 +132,26 @@ public class PluginRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(2, result.Value.Count()); - Assert.Contains(result.Value, plugin => plugin.Id == plugins[0].Id); - Assert.Contains(result.Value, plugin => plugin.Id == plugins[1].Id); + Assert.Equal(2, result.Value.Data.Count); + Assert.Contains(result.Value.Data, plugin => plugin.Id == plugins[0].Id); + Assert.Contains(result.Value.Data, plugin => plugin.Id == plugins[1].Id); } [Fact] public async Task GetAllAsync_WhenNoPluginsExist_ShouldReturnEmptyList() { // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Empty(result.Value); + Assert.Empty(result.Value.Data); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs index 36295884..6b08bdc2 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobExecutionRepositoryTests.cs @@ -46,7 +46,7 @@ public class ScheduledJobExecutionRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(execution.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(execution.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -59,7 +59,7 @@ public class ScheduledJobExecutionRepositoryTests public async Task GetByIdAsync_WhenExecutionDoesNotExist_ShouldReturnNull() { // Act - Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs index b45c6ff8..815d517b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Scheduling/ScheduledJobRepositoryTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Scheduling; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Scheduling; using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.UoW; @@ -47,7 +49,7 @@ public class ScheduledJobRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(scheduledJob.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(scheduledJob.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -60,7 +62,7 @@ public class ScheduledJobRepositoryTests public async Task GetByIdAsync_WhenScheduledJobDoesNotExist_ShouldReturnNull() { // Act - Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -106,11 +108,11 @@ public class ScheduledJobRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); - Assert.Equal(2, result.Value.Count()); + Assert.Equal(2, result.Value.Data.Count); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs index e91ccef7..f88d9448 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Themes/ThemeRepositoryTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Themes; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; using Lumina.DataAccess.Core.Repositories.Themes; using Lumina.DataAccess.Core.UoW; @@ -82,25 +84,25 @@ public class ThemeRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(3, result.Value.Count()); - Assert.Equal(themes, result.Value); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(themes, result.Value.Data); } [Fact] public async Task GetAllAsync_WhenNoThemesExist_ShouldReturnEmptyList() { // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Empty(result.Value); + Assert.Empty(result.Value.Data); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs index 8f754788..b261db64 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -2,6 +2,8 @@ using EntityFrameworkCore.Testing.NSubstitute; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Repositories.Users; @@ -88,25 +90,25 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Equal(3, result.Value.Count()); - Assert.Equal(users, result.Value); + Assert.Equal(3, result.Value.Data.Count); + Assert.Equal(users, result.Value.Data); } [Fact] public async Task GetAllAsync_WhenNoUsersExist_ShouldReturnEmptyList() { // Act - Result> result = await _sut.GetAllAsync(CancellationToken.None); + Result> result = await _sut.GetAllAsync(cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); Assert.NotNull(result.Value); - Assert.Empty(result.Value); + Assert.Empty(result.Value.Data); } [Fact] @@ -180,6 +182,35 @@ public class UserRepositoryTests Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError); } + [Fact] + public async Task UpdateAsync_WhenIncomingEntityCarriesADifferentId_ShouldPreserveTheStoredIdentity() + { + // Arrange + UserEntity existingUser = _userEntityFixture.Create(); + _mockContext.Users.Add(existingUser); + await _mockContext.SaveChangesAsync(); + + Guid mismatchedId = Guid.NewGuid(); + UserEntity updatedUser = _userEntityFixture.Create(id: mismatchedId, username: existingUser.Username, password: "NewPassword123"); + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.CreatedBy = existingUser.CreatedBy; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; + + // Act + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + // The repository locates the row by username, so the stored identity must survive an incoming key that does not match it. + EntityEntry trackedUser = _mockContext.ChangeTracker.Entries() + .Single(entry => entry.Entity.Username == existingUser.Username); + Assert.Equal(existingUser.Id, trackedUser.Entity.Id); + Assert.NotEqual(mismatchedId, trackedUser.Entity.Id); + Assert.Equal("NewPassword123", trackedUser.Entity.Password); + } + [Fact] public async Task GetByIdAsync_WhenUserExists_ShouldReturnUserWithAllRelations() { @@ -189,7 +220,7 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(userModel.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(userModel.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -209,7 +240,7 @@ public class UserRepositoryTests Guid nonExistentId = Guid.NewGuid(); // Act - Result result = await _sut.GetByIdAsync(nonExistentId, CancellationToken.None); + Result result = await _sut.GetByIdAsync(nonExistentId, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -254,7 +285,7 @@ public class UserRepositoryTests } [Fact] - public async Task UpdateAsync_WhenUserHasExistingPermissions_ShouldRemoveOldPermissionsAndAddNew() + public async Task UpdateAsync_WhenThePermissionsAreReplaced_ShouldRemoveTheOldAndAddTheNew() { // Arrange UserEntity existingUser = _userEntityFixture.Create(); @@ -296,6 +327,57 @@ public class UserRepositoryTests Assert.Equal(newPermission.Id, addedPermission.Entity.PermissionId); } + [Fact] + public async Task UpdateAsync_WhenAPermissionIsStillPresent_ShouldKeepItsIdentityAndAuditColumns() + { + // Arrange + UserEntity existingUser = _userEntityFixture.Create(); + PermissionEntity keptPermission = _permissionEntityFixture.Create(); + PermissionEntity removedPermission = _permissionEntityFixture.Create(); + + DateTime keptCreatedOnUtc = new(2020, 5, 6, 7, 8, 9, DateTimeKind.Utc); + UserPermissionEntity keptUserPermission = _userPermissionEntityFixture.Create(existingUser, keptPermission); + keptUserPermission.CreatedOnUtc = keptCreatedOnUtc; + UserPermissionEntity removedUserPermission = _userPermissionEntityFixture.Create(existingUser, removedPermission); + + UserEntity userWithPermissions = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userPermissions: [keptUserPermission, removedUserPermission], includeUserPermissions: true); + userWithPermissions.CreatedOnUtc = existingUser.CreatedOnUtc; + userWithPermissions.CreatedBy = existingUser.CreatedBy; + + _mockContext.Users.Add(userWithPermissions); + _mockContext.Permissions.Add(keptPermission); + _mockContext.Permissions.Add(removedPermission); + await _mockContext.SaveChangesAsync(); + + UserPermissionEntity incomingKeptPermission = _userPermissionEntityFixture.Create(userWithPermissions, keptPermission); + UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: "NewPassword", userPermissions: [incomingKeptPermission], includeUserPermissions: true); + updatedUser.CreatedBy = existingUser.CreatedBy; + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; + + // Act + Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + UserEntity? modifiedUser = await _mockContext.Users + .Include(u => u.UserPermissions) + .FirstOrDefaultAsync(u => u.Username == existingUser.Username); + Assert.NotNull(modifiedUser); + UserPermissionEntity retainedPermission = Assert.Single(modifiedUser.UserPermissions); + Assert.Equal(keptUserPermission.Id, retainedPermission.Id); + Assert.Equal(keptPermission.Id, retainedPermission.PermissionId); + Assert.Equal(keptCreatedOnUtc, retainedPermission.CreatedOnUtc); + + EntityEntry? removedEntry = _mockContext.ChangeTracker + .Entries() + .FirstOrDefault(e => e.Entity.PermissionId == removedPermission.Id); + Assert.NotNull(removedEntry); + Assert.Equal(EntityState.Deleted, removedEntry.State); + } + [Fact] public async Task UpdateAsync_WhenUserRoleChanges_ShouldRemoveOldRoleAndAddNew() { diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs index 7c0a0164..c5997a4b 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs @@ -81,7 +81,7 @@ public class UserSettingsRepositoryTests await _mockContext.SaveChangesAsync(); // Act - Result result = await _sut.GetByIdAsync(settings.Id, CancellationToken.None); + Result result = await _sut.GetByIdAsync(settings.Id, cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -94,7 +94,7 @@ public class UserSettingsRepositoryTests public async Task GetByIdAsync_WhenSettingsDoNotExist_ShouldReturnNull() { // Act - Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), cancellationToken: CancellationToken.None); // Assert Assert.False(result.IsFailure); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index 3ff2ee59..67b3fa86 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -6,6 +6,8 @@ using Lumina.Application.Common.DataAccess.Repositories.Authorization; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; @@ -47,6 +49,7 @@ public class DataSeedServiceTests public DataSeedServiceTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockDateTimeProvider = Substitute.For(); _mockPermissionRepository = Substitute.For(); _fixedUtcNow = DateTime.UtcNow; @@ -252,7 +255,15 @@ public class DataSeedServiceTests _mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(permissions); + mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(new PaginatedResultDto + { + Data = permissions, + CurrentPage = 1, + PerPage = permissions.Count, + Count = permissions.Count, + NumberOfPages = 1 + }); mockRolePermissionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); // Act @@ -310,7 +321,7 @@ public class DataSeedServiceTests _mockUnitOfWork.PermissionRepository.Returns(mockPermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(expectedError); + mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(expectedError); // Act Result result = await _sut.SetAdminRolePermissionsAsync(userId, CancellationToken.None); @@ -340,7 +351,15 @@ public class DataSeedServiceTests _mockUnitOfWork.RolePermissionRepository.Returns(mockRolePermissionRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockPermissionRepository.GetAllAsync(Arg.Any()).Returns(permissions); + mockPermissionRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(new PaginatedResultDto + { + Data = permissions, + CurrentPage = 1, + PerPage = permissions.Count, + Count = permissions.Count, + NumberOfPages = 1 + }); mockRolePermissionRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(expectedError); // Act @@ -396,7 +415,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(adminUser); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns(adminUser); mockUserRoleRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(Result.Created); // Act @@ -454,7 +473,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRepository.Returns(mockUserRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns((UserEntity?)null); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns((UserEntity?)null); // Act Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); @@ -485,7 +504,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRoleRepository.Returns(mockUserRoleRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(adminUser); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns(adminUser); mockUserRoleRepository.InsertAsync(Arg.Any(), Arg.Any()).Returns(expectedError); // Act @@ -537,7 +556,7 @@ public class DataSeedServiceTests _mockUnitOfWork.UserRepository.Returns(mockUserRepository); mockRoleRepository.GetByNameAsync("Admin", Arg.Any()).Returns(adminRole); - mockUserRepository.GetByIdAsync(userId, Arg.Any()).Returns(expectedError); + mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()).Returns(expectedError); // Act Result result = await _sut.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None); @@ -580,7 +599,7 @@ public class DataSeedServiceTests await mockScheduledJobRepository.Received(5).InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); - await mockScheduledJobRepository.DidNotReceive().GetAllAsync(Arg.Any()); + await mockScheduledJobRepository.DidNotReceive().GetAllAsync(cancellationToken: Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 4ae099c4..3def4bad 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Time; using Lumina.DataAccess.Common.DependencyInjection; using Lumina.DataAccess.Core.UoW; using Lumina.DataAccess.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -55,6 +56,9 @@ public class UnitOfWorkTests yield return new object[] { nameof(IUnitOfWork.RoleRepository), (Func)(unitOfWork => unitOfWork.RoleRepository) }; yield return new object[] { nameof(IUnitOfWork.UserRoleRepository), (Func)(unitOfWork => unitOfWork.UserRoleRepository) }; yield return new object[] { nameof(IUnitOfWork.BookRepository), (Func)(unitOfWork => unitOfWork.BookRepository) }; + yield return new object[] { nameof(IUnitOfWork.ArtistRepository), (Func)(unitOfWork => unitOfWork.ArtistRepository) }; + yield return new object[] { nameof(IUnitOfWork.AlbumRepository), (Func)(unitOfWork => unitOfWork.AlbumRepository) }; + yield return new object[] { nameof(IUnitOfWork.TrackRepository), (Func)(unitOfWork => unitOfWork.TrackRepository) }; yield return new object[] { nameof(IUnitOfWork.MediaContributorRepository), (Func)(unitOfWork => unitOfWork.MediaContributorRepository) }; yield return new object[] { nameof(IUnitOfWork.DirectoryScanFingerprintRepository), (Func)(unitOfWork => unitOfWork.DirectoryScanFingerprintRepository) }; yield return new object[] { nameof(IUnitOfWork.LibraryRepository), (Func)(unitOfWork => unitOfWork.LibraryRepository) }; @@ -96,9 +100,11 @@ public class UnitOfWorkTests CancellationToken cancellationToken = new(); // Act - await unitOfWork.SaveChangesAsync(cancellationToken); + Result result = await unitOfWork.SaveChangesAsync(cancellationToken); // Assert + Assert.True(result.IsSuccess); + Assert.Equal(Result.Success, result.Value); await dbContext.Received(1).SaveChangesAsync(cancellationToken); } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs index 9974f0b9..30dcc914 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; [ExcludeFromCodeCoverage] public class AudioContentTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void AudioContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class AudioContentTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (AudioContentType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - AudioContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs index eaca2935..ddc815cd 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; [ExcludeFromCodeCoverage] public class AudioRatingSourceTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void AudioRatingSource_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class AudioRatingSourceTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (AudioRatingSource value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - AudioRatingSource deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs index f733df6a..ebc66261 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Authorization; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Authorization; [ExcludeFromCodeCoverage] public class AuthorizationPermissionTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void AuthorizationPermission_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,7 +21,6 @@ public class AuthorizationPermissionTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); } [Fact] @@ -41,20 +32,4 @@ public class AuthorizationPermissionTests // Assert Assert.Equal(0, value); } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (AuthorizationPermission value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - AuthorizationPermission deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } - } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs index fb847fae..ea588c1c 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; [ExcludeFromCodeCoverage] public class BookFormatTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void BookFormat_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class BookFormatTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (BookFormat value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - BookFormat deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs index 1744a9f2..364b6530 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; [ExcludeFromCodeCoverage] public class BookRatingSourceTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void BookRatingSource_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class BookRatingSourceTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (BookRatingSource value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - BookRatingSource deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs index 91f47119..12e397bd 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; [ExcludeFromCodeCoverage] public class IsbnFormatTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void IsbnFormat_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class IsbnFormatTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (IsbnFormat value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - IsbnFormat deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs index 99393ae6..5c52d627 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; [ExcludeFromCodeCoverage] public class MetadataStatusTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void MetadataStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class MetadataStatusTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (MetadataStatus value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - MetadataStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs index e8b81ddd..fa110d33 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; [ExcludeFromCodeCoverage] public class WrittenContentTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void WrittenContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class WrittenContentTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (WrittenContentType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - WrittenContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs index cc336912..01d775fb 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Common; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Common; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Common; [ExcludeFromCodeCoverage] public class SortOrderTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void SortOrder_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,7 +21,6 @@ public class SortOrderTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); } [Fact] @@ -41,20 +32,4 @@ public class SortOrderTests // Assert Assert.Equal(0, value); } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (SortOrder value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - SortOrder deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } - } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs index 3fc3d53c..e5a3f5da 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; [ExcludeFromCodeCoverage] public class FileAccessModeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void FileAccessMode_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class FileAccessModeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (FileAccessMode value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - FileAccessMode deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs index d15ebe21..28f965c4 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; [ExcludeFromCodeCoverage] public class FileSystemItemStatusTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void FileSystemItemStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class FileSystemItemStatusTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (FileSystemItemStatus value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - FileSystemItemStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs index 8bc0abb0..80865087 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; [ExcludeFromCodeCoverage] public class FileSystemItemTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void FileSystemItemType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class FileSystemItemTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (FileSystemItemType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - FileSystemItemType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs index 07e2facc..70418c6e 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; [ExcludeFromCodeCoverage] public class PlatformTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void PlatformType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class PlatformTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (PlatformType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - PlatformType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs index 804f53f5..29f50e72 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; [ExcludeFromCodeCoverage] public class LibraryScanFileStatusTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void LibraryScanFileStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class LibraryScanFileStatusTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (LibraryScanFileStatus value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - LibraryScanFileStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs index 6831483b..fec9445d 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; [ExcludeFromCodeCoverage] public class LibraryScanJobStatusTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void LibraryScanJobStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class LibraryScanJobStatusTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (LibraryScanJobStatus value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - LibraryScanJobStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs index 72cffd07..bbe83e16 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; [ExcludeFromCodeCoverage] public class LibraryTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void LibraryType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,7 +21,6 @@ public class LibraryTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); } [Fact] @@ -41,20 +32,4 @@ public class LibraryTypeTests // Assert Assert.Equal(0, value); } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (LibraryType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - LibraryType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } - } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs index 660fd599..6c1222d3 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; [ExcludeFromCodeCoverage] public class MiscellaneousContentTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void MiscellaneousContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class MiscellaneousContentTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (MiscellaneousContentType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - MiscellaneousContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs index 14ffd398..cd6107eb 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.PhotoLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.PhotoLibrary; [ExcludeFromCodeCoverage] public class ImageTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void ImageType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,7 +21,6 @@ public class ImageTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); } [Fact] @@ -41,20 +32,4 @@ public class ImageTypeTests // Assert Assert.Equal(0, value); } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (ImageType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - ImageType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } - } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs index 13653fac..3972ba29 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.PhotoLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.PhotoLibrary; [ExcludeFromCodeCoverage] public class VisualContentTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void VisualContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class VisualContentTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (VisualContentType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - VisualContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs index f68efa56..0e0d0891 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Plugins; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Plugins; [ExcludeFromCodeCoverage] public class PluginLoadStatusTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void PluginLoadStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class PluginLoadStatusTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (PluginLoadStatus value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - PluginLoadStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs index ba05807b..20f264eb 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Plugins; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Plugins; [ExcludeFromCodeCoverage] public class PluginSettingTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void PluginSettingType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class PluginSettingTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (PluginSettingType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - PluginSettingType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs index 0aaa4dc7..fde3eab2 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Primitives; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Primitives; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Primitives; [ExcludeFromCodeCoverage] public class ErrorTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void ErrorType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class ErrorTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (ErrorType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - ErrorType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs index 040d5e45..2c83773a 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.VideoLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.VideoLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.VideoLibrary; [ExcludeFromCodeCoverage] public class VideoContentTypeTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void VideoContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class VideoContentTypeTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (VideoContentType value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - VideoContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs index 53eeb246..e0b55437 100644 --- a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs @@ -3,8 +3,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.VideoLibrary; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Text.Json; -using System.Text.Json.Serialization; #endregion namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.VideoLibrary; @@ -15,12 +13,6 @@ namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.VideoLibrary; [ExcludeFromCodeCoverage] public class VideoRatingSourceTests { - private readonly JsonSerializerOptions _jsonOptions = new() - { - PropertyNameCaseInsensitive = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } - }; - [Fact] public void VideoRatingSource_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() { @@ -29,22 +21,5 @@ public class VideoRatingSourceTests // Assert Assert.Equal(values.Length, values.Distinct().Count()); - Assert.All(values, value => Assert.True(Enum.IsDefined(value))); - } - - [Fact] - public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() - { - // Arrange - foreach (VideoRatingSource value in Enum.GetValues()) - { - // Act - string json = JsonSerializer.Serialize(value, _jsonOptions); - VideoRatingSource deserialized = JsonSerializer.Deserialize(json, _jsonOptions); - - // Assert - Assert.Equal(value, deserialized); - Assert.StartsWith("\"", json, StringComparison.Ordinal); - } } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index f6639591..4f2edd5c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -86,7 +86,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(32, typeof(DomainErrors.Metadata).GetProperties().Length); + Assert.Equal(31, typeof(DomainErrors.Metadata).GetProperties().Length); AssertError(DomainErrors.Metadata.MetadataCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.Metadata.TitleCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Metadata.TitleMustBeMaximum255CharactersLong, ErrorType.Validation); @@ -118,7 +118,6 @@ public class ErrorsTests AssertError(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingVoteCountMustBePositive, ErrorType.Validation); AssertError(DomainErrors.Metadata.RatingsListCannotBeNull, ErrorType.Validation); - AssertError(DomainErrors.Metadata.InvalidIsoCode, ErrorType.Validation); } [Fact] @@ -126,7 +125,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(29, typeof(DomainErrors.WrittenContent).GetProperties().Length); + Assert.Equal(31, typeof(DomainErrors.WrittenContent).GetProperties().Length); AssertError(DomainErrors.WrittenContent.BookAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.IsbnListCannotBeNull, ErrorType.Validation); @@ -153,6 +152,8 @@ public class ErrorsTests AssertError(DomainErrors.WrittenContent.VolumeNumberMustBeGreaterThanZero, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookLibraryCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookPathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookPathMustBeMaximum2048CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.BookPathMustBeWithinLibraryContentLocations, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookIdCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookCoverCannotBeNull, ErrorType.Validation); AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound); @@ -163,8 +164,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(9, typeof(DomainErrors.MediaContributor).GetProperties().Length); - AssertError(DomainErrors.MediaContributor.ContributorsListCannotBeNull, ErrorType.Validation); + Assert.Equal(12, typeof(DomainErrors.MediaContributor).GetProperties().Length); AssertError(DomainErrors.MediaContributor.ContributorNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorDisplayNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong, ErrorType.Validation); @@ -173,6 +173,10 @@ public class ErrorsTests AssertError(DomainErrors.MediaContributor.RoleNameMustBeMaximum50CharactersLong, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.RoleCategoryCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.MediaContributor.ContributorRoleCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.ContributorsListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.MediaContributorIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.MediaContributorNotFound, ErrorType.NotFound); + AssertError(DomainErrors.MediaContributor.UnknownMediaContributorRole, ErrorType.Validation); } [Fact] @@ -190,7 +194,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(19, typeof(DomainErrors.FileSystemManagement).GetProperties().Length); + Assert.Equal(20, typeof(DomainErrors.FileSystemManagement).GetProperties().Length); AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.PathMustBeMaximum260CharactersLong, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.FileCopyError, ErrorType.Failure); @@ -206,6 +210,7 @@ public class ErrorsTests AssertError(DomainErrors.FileSystemManagement.BitrateMustBeAPositiveNumber, ErrorType.Validation); AssertError(DomainErrors.FileSystemManagement.CannotNavigateUp, ErrorType.Failure); AssertError(DomainErrors.FileSystemManagement.NameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.FileNameCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.FileSystemManagement.FileAlreadyExists, ErrorType.Conflict); AssertError(DomainErrors.FileSystemManagement.DirectoryNotFound, ErrorType.NotFound); AssertError(DomainErrors.FileSystemManagement.DirectoryAlreadyExists, ErrorType.Conflict); @@ -217,8 +222,7 @@ public class ErrorsTests { // Assert // The count assertion fails when an error is added or removed, reminding to update the assertions below. - Assert.Equal(9, typeof(DomainErrors.Reading).GetProperties().Length); - AssertError(DomainErrors.Reading.BookIdCannotBeEmpty, ErrorType.Validation); + Assert.Equal(8, typeof(DomainErrors.Reading).GetProperties().Length); AssertError(DomainErrors.Reading.LocationRefCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Reading.ResourceKeyCannotBeEmpty, ErrorType.Validation); AssertError(DomainErrors.Reading.BookNotFound, ErrorType.NotFound); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs index 5177711f..c3aa2089 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -109,11 +110,11 @@ public class EntityTests // Act entity.CreatedOnUtc = createdOnUtc; - entity.UpdatedOnUtc = updatedOnUtc; + entity.UpdatedOnUtc = Optional.Some(updatedOnUtc); // Assert Assert.Equal(createdOnUtc, entity.CreatedOnUtc); - Assert.Equal(updatedOnUtc, entity.UpdatedOnUtc); + Assert.Equal(Optional.Some(updatedOnUtc), entity.UpdatedOnUtc); } /// diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs index 813c16c5..22255b72 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs @@ -2,7 +2,6 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -51,21 +50,6 @@ public class BaseMetadataTests Assert.False(metadata.OriginalLanguage.HasValue); } - [Fact] - public void Constructor_WhenTitleIsNull_ShouldThrowArgumentNullException() - { - // Act & Assert - Assert.Throws(() => new TestMetadata( - null!, - Optional.None(), - Optional.None(), - _releaseInfoFixture.Create(), - [], - [], - Optional.None(), - Optional.None())); - } - [Fact] public void Equals_WithSameData_ShouldReturnTrue() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs index 957512d2..85c738a2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs @@ -34,7 +34,7 @@ public class GenreTests public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) { // Act - Result result = Genre.Create(name); + Result result = Genre.Create(name!); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs index 12cd4adb..38e8b312 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using DomainErrors = Lumina.Domain.Common.Errors.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; @@ -20,56 +19,25 @@ public class LanguageInfoTests public void Create_WhenCalledWithValidValues_ShouldCreateLanguageInfoWithLowercaseCode() { // Act - Result result = LanguageInfo.Create("EN", "English", Optional.Some("English")); + LanguageInfo result = LanguageInfo.Create("EN", "English", Optional.Some("English")); // Assert - Assert.False(result.IsFailure); - Assert.Equal("en", result.Value.LanguageCode); - Assert.Equal("English", result.Value.LanguageName); - Assert.True(result.Value.NativeName.HasValue); - Assert.Equal("English", result.Value.NativeName.Value); + Assert.Equal("en", result.LanguageCode); + Assert.Equal("English", result.LanguageName); + Assert.True(result.NativeName.HasValue); + Assert.Equal("English", result.NativeName.Value); } - [Theory] - [InlineData(null)] // null language code - [InlineData("")] // empty language code - [InlineData(" ")] // whitespace language code - public void Create_WhenLanguageCodeIsNullOrWhitespace_ShouldReturnError(string? languageCode) + [Fact] + public void Create_WhenNativeNameIsMissing_ShouldCreateLanguageInfoWithoutNativeName() { // Act - Result result = LanguageInfo.Create(languageCode, "English", Optional.None()); + LanguageInfo result = LanguageInfo.Create("en", "English", Optional.None()); // Assert - Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, result.FirstError); - } - - [Theory] - [InlineData(null)] // null language name - [InlineData("")] // empty language name - [InlineData(" ")] // whitespace language name - public void Create_WhenLanguageNameIsNullOrWhitespace_ShouldReturnError(string? languageName) - { - // Act - Result result = LanguageInfo.Create("en", languageName, Optional.None()); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Metadata.LanguageNameCannotBeEmpty, result.FirstError); - } - - [Theory] - [InlineData("e")] // single character code - [InlineData("eng")] // three character code - [InlineData("english")] // long code - public void Create_WhenLanguageCodeIsNotTwoCharactersLong_ShouldReturnError(string languageCode) - { - // Act - Result result = LanguageInfo.Create(languageCode, "English", Optional.None()); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(DomainErrors.Metadata.InvalidIsoCode, result.FirstError); + Assert.Equal("en", result.LanguageCode); + Assert.Equal("English", result.LanguageName); + Assert.False(result.NativeName.HasValue); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/MoodTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/MoodTests.cs new file mode 100644 index 00000000..daf3c9c3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/MoodTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MoodTests +{ + private readonly MoodFixture _moodFixture = new(); + + [Fact] + public void Create_WhenCalledWithUntrimmedName_ShouldTrimTheName() + { + // Act + Result result = Mood.Create(" calm "); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("calm", result.Value.Name); + } + + [Theory] + [InlineData(null)] // null mood name + [InlineData("")] // empty mood name + [InlineData(" ")] // whitespace mood name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Act + Result result = Mood.Create(name!); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.MoodNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnName() + { + // Arrange + Mood mood = _moodFixture.Create(name: "energetic"); + + // Act + string result = mood.ToString(); + + // Assert + Assert.Equal("energetic", result); + } + + [Fact] + public void Equals_WithSameName_ShouldReturnTrue() + { + // Arrange + Mood firstMood = _moodFixture.Create(name: "calm"); + Mood secondMood = _moodFixture.Create(name: "calm"); + + // Act + bool result = firstMood.Equals(secondMood); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentName_ShouldReturnFalse() + { + // Arrange + Mood firstMood = _moodFixture.Create(name: "calm"); + Mood secondMood = _moodFixture.Create(name: "energetic"); + + // Act + bool result = firstMood.Equals(secondMood); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs index b441bcc8..8135eae7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs @@ -34,7 +34,7 @@ public class TagTests public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) { // Act - Result result = Tag.Create(name); + Result result = Tag.Create(name!); // Assert Assert.True(result.IsFailure); 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 62a5d10d..9dc21ced 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 @@ -20,6 +20,7 @@ public class AudioMetadataTests private readonly GenreFixture _genreFixture = new(); private readonly TagFixture _tagFixture = new(); private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); private readonly AudioMetadataFixture _audioMetadataFixture = new(); [Fact] @@ -27,13 +28,13 @@ public class AudioMetadataTests { // Act Result result = AudioMetadata.Create( - "Abbey Road", + "Bohemian Rhapsody", Optional.None(), durationInSeconds: 2826, sampleRate: 44100, channels: 2, _releaseInfoFixture.Create(), - Optional.Some("The last recorded album by the Beatles."), + Optional.Some("A song by the British rock band Queen."), [_genreFixture.Create(name: "Rock")], [_tagFixture.Create(name: "classic")], Optional.None(), @@ -44,11 +45,11 @@ public class AudioMetadataTests // Assert Assert.False(result.IsFailure); - Assert.Equal("Abbey Road", result.Value.Title); + Assert.Equal("Bohemian Rhapsody", result.Value.Title); Assert.Equal(2826, result.Value.DurationInSeconds); Assert.Equal(44100, result.Value.SampleRate); Assert.Equal(2, result.Value.Channels); - Assert.Equal("The last recorded album by the Beatles.", result.Value.Description.Value); + Assert.Equal("A song by the British rock band Queen.", result.Value.Description.Value); Assert.Equal(16, result.Value.BitDepth.Value); Assert.Equal("PCM", result.Value.AudioCodec.Value); Assert.Equal(1411, result.Value.Bitrate.Value); @@ -61,7 +62,7 @@ public class AudioMetadataTests { // Act Result result = AudioMetadata.Create( - "Abbey Road", + "Bohemian Rhapsody", Optional.None(), durationInSeconds: 2826, sampleRate: 44100, @@ -91,7 +92,7 @@ public class AudioMetadataTests // Act AudioMetadata firstResult = _audioMetadataFixture.Create( - title: "Abbey Road", + title: "Bohemian Rhapsody", originalTitle: Optional.None(), durationInSeconds: 2826, sampleRate: 44100, @@ -106,7 +107,7 @@ public class AudioMetadataTests audioCodec: Optional.None(), bitrate: Optional.None()); AudioMetadata secondResult = _audioMetadataFixture.Create( - title: "Abbey Road", + title: "Bohemian Rhapsody", originalTitle: Optional.None(), durationInSeconds: 2826, sampleRate: 44100, @@ -133,7 +134,7 @@ public class AudioMetadataTests // Act AudioMetadata firstResult = _audioMetadataFixture.Create( - title: "Abbey Road", + title: "Bohemian Rhapsody", originalTitle: Optional.None(), durationInSeconds: 2826, sampleRate: 44100, @@ -148,7 +149,7 @@ public class AudioMetadataTests audioCodec: Optional.None(), bitrate: Optional.None()); AudioMetadata secondResult = _audioMetadataFixture.Create( - title: "Abbey Road", + title: "Bohemian Rhapsody", originalTitle: Optional.None(), durationInSeconds: 2826, sampleRate: 48000, @@ -166,4 +167,192 @@ public class AudioMetadataTests // Assert Assert.NotEqual(firstResult, secondResult); } + + [Fact] + public void Create_WhenOptionalBaseValuesArePresent_ShouldSetThem() + { + // Arrange + LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English"); + LanguageInfo originalLanguage = _languageInfoFixture.Create(languageCode: "fr", languageName: "French"); + + // Act + Result result = AudioMetadata.Create( + "Bohemian Rhapsody", + Optional.Some("Bohemian Rhapsody (original)"), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + _releaseInfoFixture.Create(), + Optional.Some("A song by the British rock band Queen."), + [_genreFixture.Create(name: "Rock")], + [_tagFixture.Create(name: "classic")], + Optional.Some(language), + Optional.Some(originalLanguage), + Optional.Some(16), + Optional.Some("PCM"), + Optional.Some(1411)); + + // Assert + Assert.False(result.IsFailure); + AudioMetadata metadata = result.Value; + Assert.Equal("Bohemian Rhapsody", metadata.Title); + Assert.Equal(Optional.Some("Bohemian Rhapsody (original)"), metadata.OriginalTitle); + Assert.Equal(Optional.Some("A song by the British rock band Queen."), metadata.Description); + Assert.Equal(Optional.Some(language), metadata.Language); + Assert.Equal(Optional.Some(originalLanguage), metadata.OriginalLanguage); + Assert.Single(metadata.Genres); + Assert.Single(metadata.Tags); + } + + [Fact] + public void Create_WhenCollectionsAreEmpty_ShouldCreateMetadataWithEmptyCollections() + { + // Act + Result result = AudioMetadata.Create( + "Bohemian Rhapsody", + Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + _releaseInfoFixture.Create(), + Optional.None(), + [], + [], + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Genres); + Assert.Empty(result.Value.Tags); + } + + [Fact] + public void Equals_WithDifferentTitle_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AudioMetadata firstResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + AudioMetadata secondResult = _audioMetadataFixture.Create( + title: "Love of My Life", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } + + [Fact] + public void Equals_WithDifferentAudioCodec_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AudioMetadata firstResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.Some("PCM"), + bitrate: Optional.None()); + AudioMetadata secondResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.Some("FLAC"), + bitrate: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } + + [Fact] + public void Equals_WithDifferentGenres_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AudioMetadata firstResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [_genreFixture.Create(name: "Rock")], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + AudioMetadata secondResult = _audioMetadataFixture.Create( + title: "Bohemian Rhapsody", + originalTitle: Optional.None(), + durationInSeconds: 355, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [_genreFixture.Create(name: "Jazz")], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRatingTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRatingTests.cs new file mode 100644 index 00000000..6b61e746 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/Common/ValueObjects/AudioRatingTests.cs @@ -0,0 +1,212 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingTests +{ + private readonly AudioRatingFixture _audioRatingFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateRatingWithAllPropertiesSet() + { + // Act + Result result = AudioRating.Create(4m, 5m, Optional.Some(AudioRatingSource.MusicBrainz), Optional.Some(10)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(4m, result.Value.Value); + Assert.Equal(5m, result.Value.MaxValue); + Assert.Equal(Optional.Some(AudioRatingSource.MusicBrainz), result.Value.Source); + Assert.Equal(Optional.Some(10), result.Value.VoteCount); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateRatingWithoutThem() + { + // Act + Result result = AudioRating.Create(3m, 5m, Optional.None(), Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Source.HasValue); + Assert.False(result.Value.VoteCount.HasValue); + } + + [Theory] + [InlineData(-1)] // negative value + [InlineData(-0.5)] // negative fractional value + public void Create_WhenValueIsNegative_ShouldReturnError(double value) + { + // Act + Result result = AudioRating.Create((decimal)value, maxValue: 5, Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.RatingValueMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenMaxValueIsNegative_ShouldReturnError() + { + // Act + Result result = AudioRating.Create(value: 4m, maxValue: -5, Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.RatingValueMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenValueIsGreaterThanMaxValue_ShouldReturnError() + { + // Act + Result result = AudioRating.Create(6m, 5m, Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError); + } + + [Fact] + public void ToString_WhenSourceAndVoteCountArePresent_ShouldIncludeThem() + { + // Arrange + AudioRating rating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.Some(AudioRatingSource.LastFm), voteCount: Optional.Some(10)); + + // Act + string result = rating.ToString(); + + // Assert + Assert.Equal("4/5 (LastFm) [10 votes]", result); + } + + [Fact] + public void ToString_WhenSourceAndVoteCountAreAbsent_ShouldReturnValueAndMaxValue() + { + // Arrange + AudioRating rating = _audioRatingFixture.Create(value: 3m, maxValue: 5m, source: Optional.None(), voteCount: Optional.None()); + + // Act + string result = rating.ToString(); + + // Assert + Assert.Equal("3/5", result); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.Some(AudioRatingSource.User), voteCount: Optional.Some(10)); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.Some(AudioRatingSource.User), voteCount: Optional.Some(10)); + + // Act + bool result = firstRating.Equals(secondRating); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m); + + // Act + bool result = firstRating.Equals(secondRating); + + // Assert + Assert.False(result); + } + + [Fact] + public void Create_WhenValueIsZero_ShouldCreateRating() + { + // Act + Result result = AudioRating.Create(0m, 5m, Optional.None(), Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0m, result.Value.Value); + } + + [Fact] + public void Create_WhenValueEqualsMaxValue_ShouldCreateRating() + { + // Act + Result result = AudioRating.Create(5m, 5m, Optional.None(), Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(5m, result.Value.Value); + Assert.Equal(5m, result.Value.MaxValue); + } + + [Fact] + public void Equals_WithDifferentMaxValue_ShouldReturnFalse() + { + // Arrange + AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.None(), voteCount: Optional.None()); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 10m, source: Optional.None(), voteCount: Optional.None()); + + // Act + bool result = firstRating.Equals(secondRating); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithDifferentSource_ShouldReturnFalse() + { + // Arrange + AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.Some(AudioRatingSource.User), voteCount: Optional.None()); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.Some(AudioRatingSource.Discogs), voteCount: Optional.None()); + + // Act + bool result = firstRating.Equals(secondRating); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithDifferentVoteCount_ShouldReturnFalse() + { + // Arrange + AudioRating firstRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.None(), voteCount: Optional.Some(10)); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m, source: Optional.None(), voteCount: Optional.Some(20)); + + // Act + bool result = firstRating.Equals(secondRating); + + // Assert + Assert.False(result); + } + + [Fact] + public void AsPercentage_WhenCalled_ShouldReturnTheValueAsPercentageOfMaxValue() + { + // Arrange + AudioRating rating = _audioRatingFixture.Create(value: 4m, maxValue: 5m); + + // Act + decimal result = rating.AsPercentage(); + + // Assert + Assert.Equal(80m, result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs new file mode 100644 index 00000000..68a5c484 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/LibraryManagementBoundedContext/LibraryAggregate/LibraryIdTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryIdTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + LibraryId libraryId = LibraryId.CreateUnique(); + + // Assert + Assert.NotEqual(Guid.Empty, libraryId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + LibraryId libraryId = LibraryId.Create(value); + + // Assert + Assert.Equal(value, libraryId.Value); + } + + [Fact] + public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue() + { + // Act + LibraryId libraryId = LibraryId.Create(Guid.Empty); + + // Assert + Assert.Equal(Guid.Empty, libraryId.Value); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + LibraryId libraryId = _libraryIdFixture.Create(value); + + // Act + string? result = libraryId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + LibraryId firstId = _libraryIdFixture.Create(value); + LibraryId secondId = _libraryIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + LibraryId firstId = _libraryIdFixture.Create(); + LibraryId secondId = _libraryIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorIdTests.cs new file mode 100644 index 00000000..5b2ea457 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/ExternalIdentifiers/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorIdTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorIdTests +{ + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + MediaContributorId mediaContributorId = MediaContributorId.CreateUnique(); + + // Assert + Assert.NotEqual(Guid.Empty, mediaContributorId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + MediaContributorId mediaContributorId = MediaContributorId.Create(value); + + // Assert + Assert.Equal(value, mediaContributorId.Value); + } + + [Fact] + public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue() + { + // Act + MediaContributorId mediaContributorId = MediaContributorId.Create(Guid.Empty); + + // Assert + Assert.Equal(Guid.Empty, mediaContributorId.Value); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + MediaContributorId mediaContributorId = _mediaContributorIdFixture.Create(value); + + // Act + string? result = mediaContributorId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + MediaContributorId firstId = _mediaContributorIdFixture.Create(value); + MediaContributorId secondId = _mediaContributorIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + MediaContributorId firstId = _mediaContributorIdFixture.Create(); + MediaContributorId secondId = _mediaContributorIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} 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 new file mode 100644 index 00000000..82eefad2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ArtistTests.cs @@ -0,0 +1,691 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +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; +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; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtistTests +{ + private readonly ArtistFixture _artistFixture = new(); + private readonly AlbumFixture _albumFixture = new(); + private readonly TrackFixture _trackFixture = new(); + private readonly ArtistIdFixture _artistIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly AlbumMetadataFixture _albumMetadataFixture = new(); + private readonly BarcodeFixture _barcodeFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); + private readonly AudioMetadataFixture _audioMetadataFixture = new(); + private readonly MoodFixture _moodFixture = new(); + private readonly IsrcFixture _isrcFixture = new(); + + [Fact] + public void AddTrackToAlbum_WhenAlbumIsOwnedByTheArtist_ShouldAddTheTrackAndReturnSuccess() + { + // Arrange + Album album = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [album]); + Track track = _trackFixture.Create(); + + // Act + Result result = artist.AddTrackToAlbum(album, track); + + // Assert + Assert.False(result.IsFailure); + Track storedTrack = Assert.Single(album.Tracks); + Assert.Equal(track, storedTrack); + } + + [Fact] + public void AddTrackToAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(tracks: []); + Album foreignAlbum = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + Track track = _trackFixture.Create(); + + // Act + Result result = artist.AddTrackToAlbum(foreignAlbum, track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Empty(foreignAlbum.Tracks); + } + + [Fact] + public void AddTrackToAlbum_WhenTrackIsAlreadyInTheAlbum_ShouldPropagateTheTrackIsAlreadyInTheAlbumError() + { + // Arrange + Album album = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [album]); + Track track = _trackFixture.Create(); + artist.AddTrackToAlbum(album, track); + + // Act + Result result = artist.AddTrackToAlbum(album, track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError); + Assert.Single(album.Tracks); + } + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateArtistWithAllProperties() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create(); + List contributors = [_musicMediaContributorFixture.Create()]; + Album album = _albumFixture.Create(); + DateTime beforeCreate = DateTime.UtcNow; + + // Act + Result result = Artist.Create( + libraryId, + "Queen", + Optional.Some("https://www.queenonline.com"), + Optional.Some(musicBrainzArtistId), + contributors, + [album]); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.NotEqual(Guid.Empty, artist.Id.Value); + Assert.Equal(libraryId, artist.LibraryId); + Assert.Equal("Queen", artist.Name); + Assert.Equal(Optional.Some("https://www.queenonline.com"), artist.Website); + Assert.Equal(Optional.Some(musicBrainzArtistId), artist.MusicBrainzArtistId); + Assert.Equal(contributors, artist.Contributors); + Assert.Single(artist.Albums); + Assert.Equal(album, artist.Albums.Single()); + Assert.InRange(artist.CreatedOnUtc, beforeCreate, DateTime.UtcNow); + Assert.False(artist.UpdatedOnUtc.HasValue); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateArtistWithoutThem() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + Album album = _albumFixture.Create(); + + // Act + Result result = Artist.Create( + libraryId, + "Queen", + Optional.None(), + Optional.None(), + [], + [album]); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.False(artist.Website.HasValue); + Assert.False(artist.MusicBrainzArtistId.HasValue); + Assert.Empty(artist.Contributors); + Assert.Single(artist.Albums); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name) + { + // Act + Result result = Artist.Create( + _libraryIdFixture.Create(), + name!, + Optional.None(), + Optional.None(), + [], + [_albumFixture.Create()]); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Act + Result result = Artist.Create( + _libraryIdFixture.Create(), + "Queen", + Optional.None(), + Optional.None(), + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } + + [Fact] + public void CreateWithId_WhenCalledWithValidData_ShouldPreserveIdentityAndTimestamps() + { + // Arrange + ArtistId artistId = _artistIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + Album album = _albumFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Artist.Create( + artistId, + libraryId, + "Queen", + Optional.Some("https://www.queenonline.com"), + Optional.None(), + [], + [album], + createdOnUtc, + Optional.Some(updatedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Artist artist = result.Value; + Assert.Equal(artistId, artist.Id); + Assert.Equal(libraryId, artist.LibraryId); + Assert.Equal("Queen", artist.Name); + Assert.Equal(Optional.Some("https://www.queenonline.com"), artist.Website); + Assert.Equal(createdOnUtc, artist.CreatedOnUtc); + Assert.Equal(Optional.Some(updatedOnUtc), artist.UpdatedOnUtc); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void CreateWithId_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyError(string? name) + { + // Act + Result result = Artist.Create( + _artistIdFixture.Create(), + _libraryIdFixture.Create(), + name!, + Optional.None(), + Optional.None(), + [], + [_albumFixture.Create()], + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void CreateWithId_WhenAlbumsListIsEmpty_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Act + Result result = Artist.Create( + _artistIdFixture.Create(), + _libraryIdFixture.Create(), + "Queen", + Optional.None(), + Optional.None(), + [], + [], + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + } + + [Fact] + public void AddAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldAddTheAlbumAndReturnSuccess() + { + // Arrange + Album firstAlbum = _albumFixture.Create(); + Album secondAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [firstAlbum]); + + // Act + Result result = artist.AddAlbum(secondAlbum); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, artist.Albums.Count); + Assert.Contains(secondAlbum, artist.Albums); + } + + [Fact] + public void AddAlbum_WhenAlbumIsAlreadyOwnedByTheArtist_ShouldReturnTheArtistAlreadyHasTheAlbumError() + { + // Arrange + Album album = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [album]); + + // Act + Result result = artist.AddAlbum(album); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheArtistAlreadyHasTheAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + + [Fact] + public void RemoveAlbum_WhenAlbumIsOwnedAndMoreThanOneAlbumExists_ShouldRemoveItAndReturnSuccess() + { + // Arrange + Album firstAlbum = _albumFixture.Create(); + Album secondAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [firstAlbum, secondAlbum]); + + // Act + Result result = artist.RemoveAlbum(firstAlbum); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(artist.Albums); + Assert.DoesNotContain(firstAlbum, artist.Albums); + Assert.Contains(secondAlbum, artist.Albums); + } + + [Fact] + public void RemoveAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnTheArtistDoesNotHaveTheAlbumError() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Album foreignAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + + // Act + Result result = artist.RemoveAlbum(foreignAlbum); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheArtistDoesNotHaveTheAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + + [Fact] + public void RemoveAlbum_WhenAlbumIsTheOnlyAlbumOfTheArtist_ShouldReturnArtistMustHaveAtLeastOneAlbumError() + { + // Arrange + Album onlyAlbum = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [onlyAlbum]); + + // Act + Result result = artist.RemoveAlbum(onlyAlbum); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistMustHaveAtLeastOneAlbum, result.FirstError); + Assert.Single(artist.Albums); + } + + [Fact] + public void UpdateContributors_WhenCalledWithNewContributors_ShouldReplaceThemInPlace() + { + // Arrange + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(); + Artist artist = _artistFixture.Create(contributors: [firstContributor]); + + // Act + artist.UpdateContributors([secondContributor]); + + // Assert + MusicMediaContributor storedContributor = Assert.Single(artist.Contributors); + Assert.Equal(secondContributor, storedContributor); + Assert.DoesNotContain(firstContributor, artist.Contributors); + } + + [Fact] + public void UpdateContributors_WhenCalledWithDuplicateContributors_ShouldKeepOnlyDistinctOnes() + { + // Arrange + MusicMediaContributor contributor = _musicMediaContributorFixture.Create(); + Artist artist = _artistFixture.Create(contributors: []); + + // Act + artist.UpdateContributors([contributor, contributor]); + + // Assert + MusicMediaContributor storedContributor = Assert.Single(artist.Contributors); + Assert.Equal(contributor, storedContributor); + } + + [Fact] + public void UpdateDetails_WhenCalledWithValidData_ShouldUpdateDetailsAndSetUpdatedOnUtc() + { + // Arrange + Artist artist = _artistFixture.Create(); + MusicBrainzId musicBrainzArtistId = _musicBrainzIdFixture.Create(); + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = artist.UpdateDetails( + "Queen", + Optional.Some("https://www.queenonline.com"), + Optional.Some(musicBrainzArtistId)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Queen", artist.Name); + Assert.Equal(Optional.Some("https://www.queenonline.com"), artist.Website); + Assert.Equal(Optional.Some(musicBrainzArtistId), artist.MusicBrainzArtistId); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate); + } + + [Fact] + public void UpdateDetails_WhenNameIsNullOrWhitespace_ShouldReturnArtistNameCannotBeEmptyErrorAndNotMutate() + { + // Arrange + Artist artist = _artistFixture.Create(name: "Queen"); + string originalName = artist.Name; + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateDetails(" ", Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.ArtistNameCannotBeEmpty, result.FirstError); + Assert.Equal(originalName, artist.Name); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void UpdateAlbum_WhenAlbumIsOwnedByTheArtist_ShouldUpdateItAndSetUpdatedOnUtc() + { + // Arrange + Album album = _albumFixture.Create(); + Artist artist = _artistFixture.Create(albums: [album]); + 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"); + Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); + List contributors = [_musicMediaContributorFixture.Create()]; + List ratings = [_audioRatingFixture.Create()]; + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = artist.UpdateAlbum( + album, + metadata, + mediaFormat, + barcode, + catalogNumber, + releaseId, + releaseGroupId, + releaseArtistId, + contributors, + ratings); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(metadata, album.Metadata); + Assert.Equal(mediaFormat, album.MediaFormat); + Assert.Equal(barcode, album.Barcode); + Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(releaseId, album.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); + Assert.Equal(contributors, album.Contributors); + Assert.Equal(ratings, album.Ratings); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate); + } + + [Fact] + public void UpdateAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundErrorAndNotMutate() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Album foreignAlbum = _albumFixture.Create(); + AlbumMetadata originalMetadata = foreignAlbum.Metadata; + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateAlbum( + foreignAlbum, + _albumMetadataFixture.Create(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Equal(originalMetadata, foreignAlbum.Metadata); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void UpdateTrackInAlbum_WhenAlbumAndTrackBelongToTheArtist_ShouldUpdateTheTrackAndSetUpdatedOnUtc() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [album]); + string path = "C:\\Music\\queen\\bohemian-rhapsody.flac"; + AudioMetadata metadata = _audioMetadataFixture.Create(); + Optional discNumber = Optional.Some(1); + Optional script = Optional.Some("Latin"); + Optional key = Optional.Some(MusicKey.BMajor); + Optional bpm = Optional.Some(72); + Optional work = Optional.Some("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()]; + List ratings = [_audioRatingFixture.Create()]; + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = artist.UpdateTrackInAlbum( + album, + track, + path, + metadata, + 11, + discNumber, + script, + key, + bpm, + work, + recordingId, + musicBrainzTrackId, + workId, + moods, + isrcs, + contributors, + ratings); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(path, track.Path); + Assert.Equal(metadata, track.Metadata); + Assert.Equal(11, track.TrackNumber); + Assert.Equal(discNumber, track.DiscNumber); + Assert.Equal(script, track.Script); + Assert.Equal(key, track.Key); + Assert.Equal(bpm, track.Bpm); + 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); + Assert.Equal(ratings, track.Ratings); + Assert.True(artist.UpdatedOnUtc.HasValue); + Assert.True(artist.UpdatedOnUtc.Value >= beforeUpdate); + } + + [Fact] + public void UpdateTrackInAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundErrorAndNotMutate() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Track track = _trackFixture.Create(); + Album foreignAlbum = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + string originalPath = track.Path; + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateTrackInAlbum( + foreignAlbum, + track, + "C:\\Music\\queen\\bohemian-rhapsody.flac", + _audioMetadataFixture.Create(), + 11, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Equal(originalPath, track.Path); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void UpdateTrackInAlbum_WhenTrackIsNotInTheAlbum_ShouldReturnTrackNotFoundErrorAndNotMutate() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [album]); + string originalPath = track.Path; + Optional originalUpdatedOnUtc = artist.UpdatedOnUtc; + + // Act + Result result = artist.UpdateTrackInAlbum( + album, + track, + "C:\\Music\\queen\\bohemian-rhapsody.flac", + _audioMetadataFixture.Create(), + 11, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + [], + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + Assert.Equal(originalPath, track.Path); + Assert.Equal(originalUpdatedOnUtc, artist.UpdatedOnUtc); + } + + [Fact] + public void RemoveTrackFromAlbum_WhenAlbumAndTrackBelongToTheArtist_ShouldRemoveTheTrackAndReturnSuccess() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [album]); + + // Act + Result result = artist.RemoveTrackFromAlbum(album, track); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(album.Tracks); + } + + [Fact] + public void RemoveTrackFromAlbum_WhenAlbumIsNotOwnedByTheArtist_ShouldReturnAlbumNotFoundError() + { + // Arrange + Album ownedAlbum = _albumFixture.Create(); + Track track = _trackFixture.Create(); + Album foreignAlbum = _albumFixture.Create(tracks: [track]); + Artist artist = _artistFixture.Create(albums: [ownedAlbum]); + + // Act + Result result = artist.RemoveTrackFromAlbum(foreignAlbum, track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.AlbumNotFound, result.FirstError); + Assert.Single(foreignAlbum.Tracks); + } + + [Fact] + public void RemoveTrackFromAlbum_WhenTrackIsNotInTheAlbum_ShouldReturnTrackNotFoundError() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: []); + Artist artist = _artistFixture.Create(albums: [album]); + + // Act + Result result = artist.RemoveTrackFromAlbum(album, track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + Assert.Empty(album.Tracks); + } +} 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 new file mode 100644 index 00000000..0c563880 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/AlbumTests.cs @@ -0,0 +1,358 @@ +#region ========================================================================= USING ===================================================================================== +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.Entities; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.Common.ValueObjects; +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; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AlbumTests +{ + private readonly AlbumFixture _albumFixture = new(); + private readonly TrackFixture _trackFixture = new(); + private readonly AlbumIdFixture _albumIdFixture = new(); + private readonly AlbumMetadataFixture _albumMetadataFixture = new(); + private readonly BarcodeFixture _barcodeFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); + + [Fact] + public void AddTrack_WhenTrackIsNotInTheAlbum_ShouldAddTheTrackAndReturnSuccess() + { + // Arrange + Album album = _albumFixture.Create(tracks: []); + Track track = _trackFixture.Create(); + + // Act + Result result = album.AddTrack(track); + + // Assert + Assert.False(result.IsFailure); + Track storedTrack = Assert.Single(album.Tracks); + Assert.Equal(track, storedTrack); + } + + [Fact] + public void AddTrack_WhenTrackIsAlreadyInTheAlbum_ShouldReturnTheTrackIsAlreadyInTheAlbumErrorAndNotAddDuplicate() + { + // Arrange + Album album = _albumFixture.Create(tracks: []); + Track track = _trackFixture.Create(); + album.AddTrack(track); + + // Act + Result result = album.AddTrack(track); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheTrackIsAlreadyInTheAlbum, result.FirstError); + Assert.Single(album.Tracks); + } + + [Fact] + public void Create_WhenCalledWithAllProperties_ShouldCreateAlbumWithAllProperties() + { + // Arrange + 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"); + Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); + List contributors = [_musicMediaContributorFixture.Create()]; + List ratings = [_audioRatingFixture.Create()]; + List tracks = [_trackFixture.Create()]; + DateTime beforeCreate = DateTime.UtcNow; + + // Act + Result result = Album.Create( + metadata, + mediaFormat, + barcode, + catalogNumber, + releaseId, + releaseGroupId, + releaseArtistId, + contributors, + ratings, + tracks); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + Assert.NotEqual(Guid.Empty, album.Id.Value); + Assert.Equal(metadata, album.Metadata); + Assert.Equal(mediaFormat, album.MediaFormat); + Assert.Equal(barcode, album.Barcode); + Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(releaseId, album.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); + Assert.Equal(contributors, album.Contributors); + Assert.Equal(ratings, album.Ratings); + Assert.Equal(tracks, album.Tracks); + Assert.InRange(album.CreatedOnUtc, beforeCreate, DateTime.UtcNow); + Assert.False(album.UpdatedOnUtc.HasValue); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateAlbumWithoutThem() + { + // Act + Result result = Album.Create( + _albumMetadataFixture.Create(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + []); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + Assert.False(album.MediaFormat.HasValue); + Assert.False(album.Barcode.HasValue); + Assert.False(album.CatalogNumber.HasValue); + Assert.False(album.MusicBrainzReleaseId.HasValue); + Assert.False(album.MusicBrainzReleaseGroupId.HasValue); + Assert.False(album.MusicBrainzReleaseArtistId.HasValue); + } + + [Fact] + public void Create_WhenCollectionsAreEmpty_ShouldCreateAlbumWithEmptyCollections() + { + // Act + Result result = Album.Create( + _albumMetadataFixture.Create(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + []); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.Contributors); + Assert.Empty(result.Value.Ratings); + Assert.Empty(result.Value.Tracks); + } + + [Fact] + public void CreateWithId_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps() + { + // Arrange + AlbumId albumId = _albumIdFixture.Create(); + AlbumMetadata metadata = _albumMetadataFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Album.Create( + albumId, + metadata, + Optional.Some(MusicMediaFormat.CD), + Optional.Some(_barcodeFixture.Create()), + Optional.Some("CAT-002"), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [], + [], + createdOnUtc, + Optional.Some(updatedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Album album = result.Value; + Assert.Equal(albumId, album.Id); + Assert.Equal(metadata, album.Metadata); + Assert.Equal(createdOnUtc, album.CreatedOnUtc); + Assert.Equal(Optional.Some(updatedOnUtc), album.UpdatedOnUtc); + } + + [Fact] + public void RemoveTrack_WhenTrackIsInTheAlbum_ShouldRemoveTrackAndReturnSuccess() + { + // Arrange + Track track = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: [track]); + + // Act + Result result = album.RemoveTrack(track); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(album.Tracks); + Assert.DoesNotContain(track, album.Tracks); + } + + [Fact] + public void RemoveTrack_WhenTrackIsNotInTheAlbum_ShouldReturnTheTrackIsNotInTheAlbumError() + { + // Arrange + Track storedTrack = _trackFixture.Create(); + Track foreignTrack = _trackFixture.Create(); + Album album = _albumFixture.Create(tracks: [storedTrack]); + + // Act + Result result = album.RemoveTrack(foreignTrack); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TheTrackIsNotInTheAlbum, result.FirstError); + Assert.Single(album.Tracks); + Assert.Equal(storedTrack, album.Tracks.Single()); + } + + [Fact] + public void UpdateContributors_WhenCalledTwice_ShouldReplaceTheContributorsInsteadOfAppending() + { + // Arrange + Album album = _albumFixture.Create(contributors: []); + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(); + album.UpdateContributors([firstContributor, _musicMediaContributorFixture.Create()]); + + // Act + album.UpdateContributors([secondContributor]); + + // Assert + MusicMediaContributor storedContributor = Assert.Single(album.Contributors); + Assert.Equal(secondContributor, storedContributor); + Assert.DoesNotContain(firstContributor, album.Contributors); + } + + [Fact] + public void UpdateContributors_WhenCalledWithEmptyCollection_ShouldClearTheContributors() + { + // Arrange + Album album = _albumFixture.Create(contributors: [_musicMediaContributorFixture.Create()]); + + // Act + album.UpdateContributors([]); + + // Assert + Assert.Empty(album.Contributors); + } + + [Fact] + public void UpdateRatings_WhenCalledTwice_ShouldReplaceTheRatingsInsteadOfAppending() + { + // Arrange + Album album = _albumFixture.Create(ratings: []); + AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m); + album.UpdateRatings([firstRating, _audioRatingFixture.Create(value: 2m, maxValue: 5m)]); + + // Act + album.UpdateRatings([secondRating]); + + // Assert + AudioRating storedRating = Assert.Single(album.Ratings); + Assert.Equal(secondRating, storedRating); + } + + [Fact] + public void UpdateRatings_WhenCalledWithEmptyCollection_ShouldClearTheRatings() + { + // Arrange + Album album = _albumFixture.Create(ratings: [_audioRatingFixture.Create()]); + + // Act + album.UpdateRatings([]); + + // Assert + Assert.Empty(album.Ratings); + } + + [Fact] + public void UpdateDetails_WhenCalled_ShouldUpdateAllDetailPropertiesAndSetUpdatedOnUtc() + { + // Arrange + Album album = _albumFixture.Create(); + List originalTracks = [.. album.Tracks]; + 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"); + Optional releaseId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseGroupId = Optional.Some(_musicBrainzIdFixture.Create()); + Optional releaseArtistId = Optional.Some(_musicBrainzIdFixture.Create()); + DateTime beforeUpdate = DateTime.UtcNow; + + // Act + Result result = album.UpdateDetails( + metadata, + mediaFormat, + barcode, + catalogNumber, + releaseId, + releaseGroupId, + releaseArtistId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(metadata, album.Metadata); + Assert.Equal(mediaFormat, album.MediaFormat); + Assert.Equal(barcode, album.Barcode); + Assert.Equal(catalogNumber, album.CatalogNumber); + Assert.Equal(releaseId, album.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, album.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, album.MusicBrainzReleaseArtistId); + Assert.True(album.UpdatedOnUtc.HasValue); + Assert.True(album.UpdatedOnUtc.Value >= beforeUpdate); + // the tracks are not part of the details update + Assert.Equal(originalTracks, album.Tracks); + } + + [Fact] + public void UpdateDetails_WhenOptionalValuesAreAbsent_ShouldClearTheOptionalProperties() + { + // Arrange + Album album = _albumFixture.Create(); + + // Act + Result result = album.UpdateDetails( + _albumMetadataFixture.Create(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(album.MediaFormat.HasValue); + Assert.False(album.Barcode.HasValue); + Assert.False(album.CatalogNumber.HasValue); + 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 new file mode 100644 index 00000000..382cc58f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Entities/TrackTests.cs @@ -0,0 +1,399 @@ +#region ========================================================================= USING ===================================================================================== +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.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.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; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TrackTests +{ + private readonly TrackFixture _trackFixture = new(); + private readonly MoodFixture _moodFixture = new(); + private readonly IsrcFixture _isrcFixture = new(); + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly AudioRatingFixture _audioRatingFixture = new(); + private readonly AudioMetadataFixture _audioMetadataFixture = new(); + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateTrackWithAllPropertiesPopulated() + { + // Arrange + DateTime beforeCreate = DateTime.UtcNow; + + // Act + Track track = _trackFixture.Create(); + + // Assert + Assert.NotNull(track); + Assert.NotNull(track.Id); + Assert.NotEqual(Guid.Empty, track.Id.Value); + Assert.False(string.IsNullOrWhiteSpace(track.Path)); + Assert.NotNull(track.Metadata); + Assert.True(track.TrackNumber > 0); + Assert.True(track.DiscNumber.HasValue); + Assert.NotEmpty(track.Moods); + Assert.True(track.Script.HasValue); + Assert.True(track.Key.HasValue); + Assert.True(track.Bpm.HasValue); + Assert.NotEmpty(track.Isrcs); + Assert.True(track.Work.HasValue); + 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); + Assert.False(track.UpdatedOnUtc.HasValue); + } + + [Fact] + public void Create_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveIdentityAndTimestamps() + { + // Arrange + Track sourceTrack = _trackFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Track.Create( + sourceTrack.Id, + sourceTrack.Path, + sourceTrack.Metadata, + sourceTrack.TrackNumber, + sourceTrack.DiscNumber, + [.. sourceTrack.Moods], + sourceTrack.Script, + sourceTrack.Key, + sourceTrack.Bpm, + [.. sourceTrack.Isrcs], + sourceTrack.Work, + sourceTrack.MusicBrainzRecordingId, + sourceTrack.MusicBrainzTrackId, + sourceTrack.MusicBrainzWorkId, + [.. sourceTrack.Contributors], + [.. sourceTrack.Ratings], + createdOnUtc, + Optional.Some(updatedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Track track = result.Value; + Assert.Equal(sourceTrack.Id, track.Id); + Assert.Equal(sourceTrack.Path, track.Path); + Assert.Equal(sourceTrack.Metadata, track.Metadata); + Assert.Equal(sourceTrack.TrackNumber, track.TrackNumber); + Assert.Equal(sourceTrack.DiscNumber, track.DiscNumber); + Assert.Equal(sourceTrack.Moods, track.Moods); + Assert.Equal(sourceTrack.Isrcs, track.Isrcs); + Assert.Equal(sourceTrack.Contributors, track.Contributors); + Assert.Equal(sourceTrack.Ratings, track.Ratings); + Assert.Equal(createdOnUtc, track.CreatedOnUtc); + Assert.Equal(Optional.Some(updatedOnUtc), track.UpdatedOnUtc); + } + + [Fact] + public void UpdateMoods_WhenCalledTwice_ShouldReplaceTheMoodsInsteadOfAppending() + { + // Arrange + Track track = _trackFixture.Create(moods: []); + Mood firstMood = _moodFixture.Create(name: "calm"); + Mood secondMood = _moodFixture.Create(name: "energetic"); + track.UpdateMoods([firstMood, _moodFixture.Create(name: "melancholic")]); + + // Act + track.UpdateMoods([secondMood]); + + // Assert + // the second call replaces the first set, it is not appended to it + Mood storedMood = Assert.Single(track.Moods); + Assert.Equal(secondMood, storedMood); + Assert.DoesNotContain(firstMood, track.Moods); + } + + [Fact] + public void UpdateIsrcs_WhenCalledTwice_ShouldReplaceTheIsrcsInsteadOfAppending() + { + // Arrange + Track track = _trackFixture.Create(isrcs: []); + Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839"); + Isrc secondIsrc = _isrcFixture.Create(value: "GBAYE0000001"); + track.UpdateIsrcs([firstIsrc, _isrcFixture.Create(value: "FRUM71400001")]); + + // Act + track.UpdateIsrcs([secondIsrc]); + + // Assert + // the second call replaces the first set, it is not appended to it + Isrc storedIsrc = Assert.Single(track.Isrcs); + Assert.Equal(secondIsrc, storedIsrc); + Assert.DoesNotContain(firstIsrc, track.Isrcs); + } + + [Fact] + public void UpdateContributors_WhenCalledTwice_ShouldReplaceTheContributorsInsteadOfAppending() + { + // Arrange + Track track = _trackFixture.Create(contributors: []); + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(); + track.UpdateContributors([firstContributor]); + + // Act + track.UpdateContributors([secondContributor]); + + // Assert + // the second call replaces the first set, it is not appended to it + MusicMediaContributor storedContributor = Assert.Single(track.Contributors); + Assert.Equal(secondContributor, storedContributor); + Assert.DoesNotContain(firstContributor, track.Contributors); + } + + [Fact] + public void UpdateRatings_WhenCalledTwice_ShouldReplaceTheRatingsInsteadOfAppending() + { + // Arrange + Track track = _trackFixture.Create(ratings: []); + AudioRating firstRating = _audioRatingFixture.Create(value: 1m, maxValue: 5m); + AudioRating secondRating = _audioRatingFixture.Create(value: 4m, maxValue: 5m); + track.UpdateRatings([firstRating]); + + // Act + track.UpdateRatings([secondRating]); + + // Assert + // the second call replaces the first set, it is not appended to it + AudioRating storedRating = Assert.Single(track.Ratings); + Assert.Equal(secondRating, storedRating); + } + + [Fact] + public void UpdateDetails_WhenCalled_ShouldUpdateAllDetailPropertiesAndSetUpdatedOnUtc() + { + // Arrange + Track track = _trackFixture.Create(); + List originalMoods = [.. track.Moods]; + string path = "C:\\Music\\queen\\bohemian-rhapsody.flac"; + AudioMetadata metadata = _audioMetadataFixture.Create(); + Optional discNumber = Optional.Some(2); + Optional script = Optional.Some("Latin"); + Optional key = Optional.Some(MusicKey.DMajor); + Optional bpm = Optional.Some(128); + Optional work = Optional.Some("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 + Result result = track.UpdateDetails( + path, + metadata, + 7, + discNumber, + script, + key, + bpm, + work, + recordingId, + trackId, + workId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(path, track.Path); + Assert.Equal(metadata, track.Metadata); + Assert.Equal(7, track.TrackNumber); + Assert.Equal(discNumber, track.DiscNumber); + Assert.Equal(script, track.Script); + Assert.Equal(key, track.Key); + Assert.Equal(bpm, track.Bpm); + 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 + Assert.Equal(originalMoods, track.Moods); + } + + [Fact] + public void Create_WhenOptionalValuesAndCollectionsAreEmpty_ShouldCreateTrackWithoutThem() + { + // Act + Track track = _trackFixture.Create( + discNumber: Optional.None(), + moods: [], + script: Optional.None(), + key: Optional.None(), + bpm: Optional.None(), + isrcs: [], + work: Optional.None(), + musicBrainzRecordingId: Optional.None(), + musicBrainzTrackId: Optional.None(), + musicBrainzWorkId: Optional.None(), + contributors: [], + ratings: []); + + // Assert + Assert.False(track.DiscNumber.HasValue); + Assert.False(track.Script.HasValue); + Assert.False(track.Key.HasValue); + Assert.False(track.Bpm.HasValue); + 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); + Assert.Empty(track.Ratings); + } + + [Fact] + public void CreateWithId_WhenCalledWithPreExistingIdAndTimestamps_ShouldPreserveAllOptionalProperties() + { + // Arrange + Track sourceTrack = _trackFixture.Create(); + DateTime createdOnUtc = DateTime.UtcNow.AddDays(-1); + DateTime updatedOnUtc = DateTime.UtcNow; + + // Act + Result result = Track.Create( + sourceTrack.Id, + sourceTrack.Path, + sourceTrack.Metadata, + sourceTrack.TrackNumber, + sourceTrack.DiscNumber, + [.. sourceTrack.Moods], + sourceTrack.Script, + sourceTrack.Key, + sourceTrack.Bpm, + [.. sourceTrack.Isrcs], + sourceTrack.Work, + sourceTrack.MusicBrainzRecordingId, + sourceTrack.MusicBrainzTrackId, + sourceTrack.MusicBrainzWorkId, + [.. sourceTrack.Contributors], + [.. sourceTrack.Ratings], + createdOnUtc, + Optional.Some(updatedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Track track = result.Value; + Assert.Equal(sourceTrack.Script, track.Script); + Assert.Equal(sourceTrack.Key, track.Key); + Assert.Equal(sourceTrack.Bpm, track.Bpm); + 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); + Assert.True(track.UpdatedOnUtc.HasValue); + Assert.Equal(updatedOnUtc, track.UpdatedOnUtc.Value); + } + + [Fact] + public void UpdateMoods_WhenCalledWithEmptyCollection_ShouldClearTheMoods() + { + // Arrange + Track track = _trackFixture.Create(moods: [_moodFixture.Create(name: "calm")]); + + // Act + track.UpdateMoods([]); + + // Assert + Assert.Empty(track.Moods); + } + + [Fact] + public void UpdateIsrcs_WhenCalledWithEmptyCollection_ShouldClearTheIsrcs() + { + // Arrange + Track track = _trackFixture.Create(isrcs: [_isrcFixture.Create(value: "USRC17607839")]); + + // Act + track.UpdateIsrcs([]); + + // Assert + Assert.Empty(track.Isrcs); + } + + [Fact] + public void UpdateContributors_WhenCalledWithEmptyCollection_ShouldClearTheContributors() + { + // Arrange + Track track = _trackFixture.Create(contributors: [.. _musicMediaContributorFixture.CreateMany()]); + + // Act + track.UpdateContributors([]); + + // Assert + Assert.Empty(track.Contributors); + } + + [Fact] + public void UpdateRatings_WhenCalledWithEmptyCollection_ShouldClearTheRatings() + { + // Arrange + Track track = _trackFixture.Create(ratings: [_audioRatingFixture.Create(value: 4m, maxValue: 5m)]); + + // Act + track.UpdateRatings([]); + + // Assert + Assert.Empty(track.Ratings); + } + + [Fact] + public void UpdateDetails_WhenOptionalValuesAreAbsent_ShouldClearTheOptionalProperties() + { + // Arrange + Track track = _trackFixture.Create(); + + // Act + Result result = track.UpdateDetails( + "C:\\Music\\queen\\bohemian-rhapsody.flac", + _audioMetadataFixture.Create(), + 11, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(track.DiscNumber.HasValue); + Assert.False(track.Script.HasValue); + Assert.False(track.Key.HasValue); + Assert.False(track.Bpm.HasValue); + 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/ValueObjects/AlbumIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumIdTests.cs new file mode 100644 index 00000000..d041cb3e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumIdTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +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 AlbumIdTests +{ + private readonly AlbumIdFixture _albumIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + AlbumId albumId = AlbumId.CreateUnique(); + + // Assert + Assert.NotEqual(Guid.Empty, albumId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + AlbumId albumId = AlbumId.Create(value); + + // Assert + Assert.Equal(value, albumId.Value); + } + + [Fact] + public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue() + { + // Act + AlbumId albumId = AlbumId.Create(Guid.Empty); + + // Assert + Assert.Equal(Guid.Empty, albumId.Value); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + AlbumId albumId = _albumIdFixture.Create(value); + + // Act + string? result = albumId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + AlbumId firstId = _albumIdFixture.Create(value); + AlbumId secondId = _albumIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + AlbumId firstId = _albumIdFixture.Create(); + AlbumId secondId = _albumIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} 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 new file mode 100644 index 00000000..a66b8e58 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/AlbumMetadataTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +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 Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +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 AlbumMetadataTests +{ + private readonly AlbumMetadataFixture _albumMetadataFixture = new(); + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + Genre genre = _genreFixture.Create(name: "Rock"); + Tag tag = _tagFixture.Create(name: "classic"); + LanguageInfo language = _languageInfoFixture.Create(languageCode: "en", languageName: "English"); + LanguageInfo originalLanguage = _languageInfoFixture.Create(languageCode: "fr", languageName: "French"); + + // Act + Result result = AlbumMetadata.Create( + "A Night at the Opera", + Optional.Some("A Night at the Opera (original)"), + 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), + Optional.Some(MusicReleaseStatus.Official), + Optional.Some(2), + 12); + + // Assert + Assert.False(result.IsFailure); + 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("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(Optional.Some(MusicReleaseStatus.Official), metadata.ReleaseStatus); + Assert.Equal(Optional.Some(2), metadata.TotalDiscs); + Assert.Equal(12, metadata.TotalTracks); + } + + [Fact] + public void Create_WhenOptionalValuesAreAbsent_ShouldCreateMetadataWithoutThem() + { + // Act + Result result = AlbumMetadata.Create( + "A Night at the Opera", + Optional.None(), + Optional.None(), + _releaseInfoFixture.Create(), + [], + [], + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + 12); + + // Assert + Assert.False(result.IsFailure); + AlbumMetadata metadata = result.Value; + Assert.False(metadata.OriginalTitle.HasValue); + Assert.False(metadata.Description.HasValue); + Assert.False(metadata.Language.HasValue); + Assert.False(metadata.OriginalLanguage.HasValue); + Assert.False(metadata.ReleaseType.HasValue); + Assert.False(metadata.ReleaseStatus.HasValue); + Assert.False(metadata.TotalDiscs.HasValue); + Assert.Empty(metadata.Genres); + Assert.Empty(metadata.Tags); + } + + [Fact] + public void Create_WhenCollectionsArePopulated_ShouldPreserveTheGenresAndTags() + { + // Arrange + Genre firstGenre = _genreFixture.Create(name: "Rock"); + Genre secondGenre = _genreFixture.Create(name: "Progressive Rock"); + Tag firstTag = _tagFixture.Create(name: "classic"); + Tag secondTag = _tagFixture.Create(name: "70s"); + List expectedGenres = [firstGenre, secondGenre]; + List expectedTags = [firstTag, secondTag]; + + // Act + Result result = AlbumMetadata.Create( + "A Night at the Opera", + Optional.None(), + Optional.None(), + _releaseInfoFixture.Create(), + expectedGenres, + expectedTags, + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + 12); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(expectedGenres, result.Value.Genres); + Assert.Equal(expectedTags, result.Value.Tags); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AlbumMetadata firstMetadata = _albumMetadataFixture.Create( + title: "A Night at the Opera", + originalTitle: Optional.None(), + 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), + releaseStatus: Optional.Some(MusicReleaseStatus.Official), + totalDiscs: Optional.Some(2), + totalTracks: 12); + AlbumMetadata secondMetadata = _albumMetadataFixture.Create( + title: "A Night at the Opera", + originalTitle: Optional.None(), + 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), + releaseStatus: Optional.Some(MusicReleaseStatus.Official), + totalDiscs: Optional.Some(2), + totalTracks: 12); + + // Assert + Assert.Equal(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentTitle_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AlbumMetadata firstMetadata = _albumMetadataFixture.Create(title: "A Night at the Opera", releaseInfo: releaseInfo); + AlbumMetadata secondMetadata = _albumMetadataFixture.Create(title: "A Day at the Races", releaseInfo: releaseInfo); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentReleaseType_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AlbumMetadata firstMetadata = _albumMetadataFixture.Create( + title: "A Night at the Opera", + releaseInfo: releaseInfo, + releaseType: Optional.Some(MusicReleaseType.Album)); + AlbumMetadata secondMetadata = _albumMetadataFixture.Create( + title: "A Night at the Opera", + releaseInfo: releaseInfo, + releaseType: Optional.Some(MusicReleaseType.Single)); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentTotalTracks_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AlbumMetadata firstMetadata = _albumMetadataFixture.Create( + title: "A Night at the Opera", + releaseInfo: releaseInfo, + totalTracks: 12); + AlbumMetadata secondMetadata = _albumMetadataFixture.Create( + title: "A Night at the Opera", + releaseInfo: releaseInfo, + totalTracks: 11); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdTests.cs new file mode 100644 index 00000000..55c65a3a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/ArtistIdTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +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 ArtistIdTests +{ + private readonly ArtistIdFixture _artistIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + ArtistId artistId = ArtistId.CreateUnique(); + + // Assert + Assert.NotEqual(Guid.Empty, artistId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + ArtistId artistId = ArtistId.Create(value); + + // Assert + Assert.Equal(value, artistId.Value); + } + + [Fact] + public void Create_WhenCalledWithEmptyGuid_ShouldReturnIdWithEmptyValue() + { + // Act + ArtistId artistId = ArtistId.Create(Guid.Empty); + + // Assert + Assert.Equal(Guid.Empty, artistId.Value); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + ArtistId artistId = _artistIdFixture.Create(value); + + // Act + string? result = artistId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + ArtistId firstId = _artistIdFixture.Create(value); + ArtistId secondId = _artistIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + ArtistId firstId = _artistIdFixture.Create(); + ArtistId secondId = _artistIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/BarcodeTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/BarcodeTests.cs new file mode 100644 index 00000000..67f805f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/BarcodeTests.cs @@ -0,0 +1,109 @@ +#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.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BarcodeTests +{ + private readonly BarcodeFixture _barcodeFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidTwelveDigitBarcode_ShouldCreateBarcode() + { + // Act + Result result = Barcode.Create("123456789012"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("123456789012", result.Value.Value); + } + + [Fact] + public void Create_WhenCalledWithValidThirteenDigitBarcode_ShouldCreateBarcode() + { + // Act + Result result = Barcode.Create("1234567890123"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("1234567890123", result.Value.Value); + } + + [Fact] + public void Create_WhenValueHasSurroundingWhitespace_ShouldTrimIt() + { + // Act + Result result = Barcode.Create(" 123456789012 "); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("123456789012", result.Value.Value); + } + + [Theory] + [InlineData(null)] // null barcode value + [InlineData("")] // empty barcode value + [InlineData(" ")] // whitespace barcode value + public void Create_WhenValueIsNullOrWhitespace_ShouldReturnBarcodeValueCannotBeEmptyError(string? value) + { + // Act + Result result = Barcode.Create(value!); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.BarcodeValueCannotBeEmpty, result.FirstError); + } + + [Theory] + [InlineData("12345678901")] // eleven digits, one too few + [InlineData("12345678901234")] // fourteen digits, one too many + [InlineData("12345678901A")] // contains a letter + [InlineData("1234-56789012")] // contains a separator + [InlineData("1234567890.2")] // contains a decimal separator + public void Create_WhenValueHasInvalidFormat_ShouldReturnInvalidFormatForBarcodeError(string value) + { + // Act + Result result = Barcode.Create(value); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.InvalidFormatForBarcode, result.FirstError); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Barcode firstBarcode = _barcodeFixture.Create(value: "123456789012"); + Barcode secondBarcode = _barcodeFixture.Create(value: "123456789012"); + + // Act + bool result = firstBarcode.Equals(secondBarcode); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + Barcode firstBarcode = _barcodeFixture.Create(value: "123456789012"); + Barcode secondBarcode = _barcodeFixture.Create(value: "1234567890123"); + + // Act + bool result = firstBarcode.Equals(secondBarcode); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/IsrcTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/IsrcTests.cs new file mode 100644 index 00000000..f2211c54 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/IsrcTests.cs @@ -0,0 +1,123 @@ +#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.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsrcTests +{ + private readonly IsrcFixture _isrcFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidIsrc_ShouldCreateIsrc() + { + // Act + Result result = Isrc.Create("USRC17607839"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("USRC17607839", result.Value.Value); + } + + [Fact] + public void Create_WhenValueHasLowercaseAndWhitespace_ShouldNormalizeToUppercaseTrimmed() + { + // Act + Result result = Isrc.Create(" usrc17607839 "); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("USRC17607839", result.Value.Value); + } + + [Theory] + [InlineData(null)] // null ISRC value + [InlineData("")] // empty ISRC value + [InlineData(" ")] // whitespace ISRC value + public void Create_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value) + { + // Act + Result result = Isrc.Create(value!); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.IsrcValueCannotBeEmpty, result.FirstError); + } + + [Theory] + [InlineData("USRC1760783")] // too short + [InlineData("USRC176078399")] // too long + [InlineData("1SRC17607839")] // country code does not start with two letters + [InlineData("USRC1760783X")] // designation segment is not purely numeric + [InlineData("USRC-7607839")] // contains an invalid character + public void Create_WhenValueHasInvalidFormat_ShouldReturnError(string value) + { + // Act + Result result = Isrc.Create(value); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.IsrcInvalidFormat, result.FirstError); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839"); + Isrc secondIsrc = _isrcFixture.Create(value: "USRC17607839"); + + // Act + bool result = firstIsrc.Equals(secondIsrc); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839"); + Isrc secondIsrc = _isrcFixture.Create(value: "GBAYE0000001"); + + // Act + bool result = firstIsrc.Equals(secondIsrc); + + // Assert + Assert.False(result); + } + + [Fact] + public void Create_WhenRegistrantCodeContainsOnlyLetters_ShouldCreateIsrc() + { + // Act + Result result = Isrc.Create("GBAAA0000001"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("GBAAA0000001", result.Value.Value); + } + + [Fact] + public void Equals_WhenValuesDifferOnlyByCase_ShouldNormalizeThemBeforeComparing() + { + // Arrange + Isrc firstIsrc = _isrcFixture.Create(value: "USRC17607839"); + Isrc secondIsrc = _isrcFixture.Create(value: "usrc17607839"); + + // Act + bool result = firstIsrc.Equals(secondIsrc); + + // Assert + Assert.True(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzIdTests.cs new file mode 100644 index 00000000..49975699 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzIdTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +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 MusicBrainzIdTests +{ + private readonly MusicBrainzIdFixture _musicBrainzIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + MusicBrainzId musicBrainzId = MusicBrainzId.Create(value); + + // Assert + Assert.Equal(value, musicBrainzId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + MusicBrainzId firstId = _musicBrainzIdFixture.Create(value); + MusicBrainzId secondId = _musicBrainzIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + MusicBrainzId firstId = _musicBrainzIdFixture.Create(); + MusicBrainzId secondId = _musicBrainzIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributorTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributorTests.cs new file mode 100644 index 00000000..2484b9a4 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicMediaContributorTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicMediaContributorTests +{ + private readonly MusicMediaContributorFixture _musicMediaContributorFixture = new(); + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + + [Fact] + public void Create_WhenCalled_ShouldReturnContributorWithContributorIdAndRole() + { + // Arrange + MediaContributorId contributorId = _mediaContributorIdFixture.Create(); + + // Act + MusicMediaContributor contributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer); + + // Assert + Assert.Equal(contributorId, contributor.ContributorId); + Assert.Equal(MediaContributorRole.Composer, contributor.Role); + } + + [Fact] + public void Equals_WithSameContributorIdAndRole_ShouldReturnTrue() + { + // Arrange + MediaContributorId contributorId = _mediaContributorIdFixture.Create(); + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer); + + // Act + bool result = firstContributor.Equals(secondContributor); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentRole_ShouldReturnFalse() + { + // Arrange + MediaContributorId contributorId = _mediaContributorIdFixture.Create(); + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Composer); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: contributorId, role: MediaContributorRole.Producer); + + // Act + bool result = firstContributor.Equals(secondContributor); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithDifferentContributorId_ShouldReturnFalse() + { + // Arrange + MusicMediaContributor firstContributor = _musicMediaContributorFixture.Create(contributorId: _mediaContributorIdFixture.Create(), role: MediaContributorRole.Composer); + MusicMediaContributor secondContributor = _musicMediaContributorFixture.Create(contributorId: _mediaContributorIdFixture.Create(), role: MediaContributorRole.Composer); + + // Act + bool result = firstContributor.Equals(secondContributor); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/TrackIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/TrackIdTests.cs new file mode 100644 index 00000000..f6801900 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/TrackIdTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +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 TrackIdTests +{ + private readonly TrackIdFixture _trackIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + TrackId trackId = TrackId.CreateUnique(); + + // Assert + Assert.NotNull(trackId); + Assert.NotEqual(default, trackId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + TrackId trackId = TrackId.Create(value); + + // Assert + Assert.Equal(value, trackId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + TrackId firstId = _trackIdFixture.Create(value); + TrackId secondId = _trackIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + TrackId firstId = _trackIdFixture.Create(); + TrackId secondId = _trackIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnTheStringRepresentationOfTheValue() + { + // Arrange + Guid value = Guid.NewGuid(); + TrackId trackId = _trackIdFixture.Create(value); + + // Act + string? result = trackId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs index b1d236ce..3934a1d0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -105,7 +105,7 @@ public class DirectoryProviderServiceTests } [Fact] - public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories() + public void GetSubdirectoryPaths_WhenShouldIncludeHiddenElementsIsFalse_ShouldExcludeHiddenDirectories() { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.Create(); @@ -126,7 +126,7 @@ public class DirectoryProviderServiceTests } [Fact] - public void GetSubdirectoryPaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories() + public void GetSubdirectoryPaths_WhenShouldIncludeHiddenElementsIsTrue_ShouldIncludeHiddenDirectories() { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.Create(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs index 4cf8069e..0a761645 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryServiceTests.cs @@ -55,7 +55,7 @@ public class DirectoryServiceTests { // Arrange string path = _pathDirTest; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); FileSystemPathId[] subPaths = [ @@ -63,7 +63,7 @@ public class DirectoryServiceTests _fileSystemPathIdFixture.Create(_pathDirTestSubDir2) ]; - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(subPaths.AsEnumerable())); foreach (FileSystemPathId subPath in subPaths) @@ -77,7 +77,7 @@ public class DirectoryServiceTests } // Act - Result> result = _sut.GetSubdirectories(path, includeHiddenElements); + Result> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -90,10 +90,10 @@ public class DirectoryServiceTests { // Arrange string invalidPath = string.Empty; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; // Act - Result> result = _sut.GetSubdirectories(invalidPath, includeHiddenElements); + Result> result = _sut.GetSubdirectories(invalidPath, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -105,14 +105,14 @@ public class DirectoryServiceTests { // Arrange string path = _pathDirTest; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetSubdirectories(path, includeHiddenElements); + Result> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -124,13 +124,13 @@ public class DirectoryServiceTests { // Arrange string path = _pathDirTest; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); FileSystemPathId subPath = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(new[] { subPath }.AsEnumerable())); _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) @@ -141,7 +141,7 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetSubdirectories(path, includeHiddenElements); + Result> result = _sut.GetSubdirectories(path, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -154,14 +154,14 @@ public class DirectoryServiceTests { // Arrange Directory parentDirectory = _directoryFixture.Create(); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId[] subPaths = [ _fileSystemPathIdFixture.Create(_pathDirTestSubDir1), _fileSystemPathIdFixture.Create(_pathDirTestSubDir2) ]; - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, shouldIncludeHiddenElements) .Returns(Result.From(subPaths.AsEnumerable())); foreach (FileSystemPathId subPath in subPaths) @@ -175,7 +175,7 @@ public class DirectoryServiceTests } // Act - Result> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + Result> result = _sut.GetSubdirectories(parentDirectory, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -188,13 +188,13 @@ public class DirectoryServiceTests { // Arrange Directory parentDirectory = _directoryFixture.Create(); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, shouldIncludeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + Result> result = _sut.GetSubdirectories(parentDirectory, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -206,12 +206,12 @@ public class DirectoryServiceTests { // Arrange Directory parentDirectory = _directoryFixture.Create(); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId subPath = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(parentDirectory.Id, shouldIncludeHiddenElements) .Returns(Result.From(new[] { subPath }.AsEnumerable())); _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) @@ -222,7 +222,7 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetSubdirectories(parentDirectory, includeHiddenElements); + Result> result = _sut.GetSubdirectories(parentDirectory, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -235,14 +235,14 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId[] subPaths = [ _fileSystemPathIdFixture.Create(_pathDirTestSubDir1), _fileSystemPathIdFixture.Create(_pathDirTestSubDir2) ]; - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(subPaths.AsEnumerable())); foreach (FileSystemPathId subPath in subPaths) @@ -256,7 +256,7 @@ public class DirectoryServiceTests } // Act - Result> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + Result> result = _sut.GetSubdirectories(pathId, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -269,13 +269,13 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + Result> result = _sut.GetSubdirectories(pathId, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -287,12 +287,12 @@ public class DirectoryServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathDirTest); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId subPath = _fileSystemPathIdFixture.Create( s_isUnix ? "/TestDir/InaccessibleSub" : @"C:\TestDir\InaccessibleSub" ); - _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, includeHiddenElements) + _mockEnvironmentContext.DirectoryProviderService.GetSubdirectoryPaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(new[] { subPath }.AsEnumerable())); _mockEnvironmentContext.DirectoryProviderService.GetFileName(subPath) @@ -303,7 +303,7 @@ public class DirectoryServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetSubdirectories(pathId, includeHiddenElements); + Result> result = _sut.GetSubdirectories(pathId, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index 8088d6fe..a84e1a26 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -89,7 +89,7 @@ public class FileProviderServiceTests } [Fact] - public void GetFilePaths_WhenIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles() + public void GetFilePaths_WhenShouldIncludeHiddenElementsIsFalse_ShouldExcludeHiddenFiles() { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.Create(); @@ -109,7 +109,7 @@ public class FileProviderServiceTests } [Fact] - public void GetFilePaths_WhenIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles() + public void GetFilePaths_WhenShouldIncludeHiddenElementsIsTrue_ShouldIncludeHiddenFiles() { // Arrange FileSystemPathId path = _fileSystemPathIdFixture.Create(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs index a2782531..1746cb24 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileServiceTests.cs @@ -64,7 +64,7 @@ public class FileServiceTests { // Arrange string path = _pathTestDir; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); FileSystemPathId[] filePaths = [ @@ -72,7 +72,7 @@ public class FileServiceTests _fileSystemPathIdFixture.Create(_pathTestDirFile2) ]; - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(filePaths.AsEnumerable())); foreach (FileSystemPathId filePath in filePaths) @@ -88,7 +88,7 @@ public class FileServiceTests } // Act - Result> result = _sut.GetFiles(path, includeHiddenElements); + Result> result = _sut.GetFiles(path, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -101,10 +101,10 @@ public class FileServiceTests { // Arrange string invalidPath = string.Empty; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; // Act - Result> result = _sut.GetFiles(invalidPath, includeHiddenElements); + Result> result = _sut.GetFiles(invalidPath, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -116,14 +116,14 @@ public class FileServiceTests { // Arrange string path = _pathTestDir; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetFiles(path, includeHiddenElements); + Result> result = _sut.GetFiles(path, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -135,11 +135,11 @@ public class FileServiceTests { // Arrange string path = _pathTestDir; - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirInaccessible); - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) @@ -152,7 +152,7 @@ public class FileServiceTests .Returns(Result.From((long?)null)); // Act - Result> result = _sut.GetFiles(path, includeHiddenElements); + Result> result = _sut.GetFiles(path, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -165,14 +165,14 @@ public class FileServiceTests { // Arrange File parentFile = _fileFixture.Create(); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId[] filePaths = [ _fileSystemPathIdFixture.Create(_pathTestDirFile1), _fileSystemPathIdFixture.Create(_pathTestDirFile2) ]; - _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, shouldIncludeHiddenElements) .Returns(Result.From(filePaths.AsEnumerable())); foreach (FileSystemPathId filePath in filePaths) @@ -188,7 +188,7 @@ public class FileServiceTests } // Act - Result> result = _sut.GetFiles(parentFile, includeHiddenElements); + Result> result = _sut.GetFiles(parentFile, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -201,13 +201,13 @@ public class FileServiceTests { // Arrange File parentFile = _fileFixture.Create(); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; - _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, shouldIncludeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetFiles(parentFile, includeHiddenElements); + Result> result = _sut.GetFiles(parentFile, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -219,10 +219,10 @@ public class FileServiceTests { // Arrange File parentFile = _fileFixture.Create(); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirInaccessible); - _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(parentFile.Id, shouldIncludeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) @@ -235,7 +235,7 @@ public class FileServiceTests .Returns(Result.From((long?)null)); // Act - Result> result = _sut.GetFiles(parentFile, includeHiddenElements); + Result> result = _sut.GetFiles(parentFile, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -248,14 +248,14 @@ public class FileServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId[] filePaths = [ _fileSystemPathIdFixture.Create(_pathTestDirFile1), _fileSystemPathIdFixture.Create(_pathTestDirFile2) ]; - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(filePaths.AsEnumerable())); foreach (FileSystemPathId filePath in filePaths) @@ -271,7 +271,7 @@ public class FileServiceTests } // Act - Result> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -284,13 +284,13 @@ public class FileServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, shouldIncludeHiddenElements); // Assert Assert.True(result.IsFailure); @@ -302,10 +302,10 @@ public class FileServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirInaccessible); - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) @@ -318,7 +318,7 @@ public class FileServiceTests .Returns(Result.From((long?)null)); // Act - Result> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); @@ -331,10 +331,10 @@ public class FileServiceTests { // Arrange FileSystemPathId pathId = _fileSystemPathIdFixture.Create(_pathTestDir); - bool includeHiddenElements = false; + bool shouldIncludeHiddenElements = false; FileSystemPathId filePath = _fileSystemPathIdFixture.Create(_pathTestDirFile1); - _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, includeHiddenElements) + _mockEnvironmentContext.FileProviderService.GetFilePaths(pathId, shouldIncludeHiddenElements) .Returns(Result.From(new[] { filePath }.AsEnumerable())); _mockEnvironmentContext.FileProviderService.GetFileName(filePath) .Returns(Result.From("File1.txt")); @@ -346,7 +346,7 @@ public class FileServiceTests .Returns(Errors.Permission.UnauthorizedAccess); // Act - Result> result = _sut.GetFiles(pathId, includeHiddenElements); + Result> result = _sut.GetFiles(pathId, shouldIncludeHiddenElements); // Assert Assert.False(result.IsFailure); 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 f87eaacc..13260534 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 @@ -131,7 +131,7 @@ public class PathServiceTests } [Fact] - public void Exists_WhenPathIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrue() + public void Exists_WhenPathIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue() { // Arrange string existingPath = @"C:\ExistingPath"; @@ -147,7 +147,7 @@ public class PathServiceTests } [Fact] - public void Exists_WhenPathIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalse() + public void Exists_WhenPathIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse() { // Arrange string existingPath = @"C:\ExistingPath"; @@ -771,4 +771,50 @@ public class PathServiceTests Assert.False(result.IsFailure); Assert.Equal(100, result.Value.Name.Length); } + + [Fact] + public void IsPathWithin_WhenBothPathsAreValid_ShouldCreatePathIdsAndDelegateToTheStrategy() + { + // Arrange + string path = @"C:\Media\Books\book.epub"; + string parentPath = @"C:\Media\Books"; + _mockPathStrategy.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); + + // Act + bool result = _sut.IsPathWithin(path, parentPath); + + // Assert + Assert.True(result); + _mockPathStrategy.Received(1).IsPathWithin( + Arg.Is(pathId => pathId.Path == path), + Arg.Is(pathId => pathId.Path == parentPath)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void IsPathWithin_WhenPathIsNotValid_ShouldReturnFalseWithoutCallingTheStrategy(string? invalidPath) + { + // Act + bool result = _sut.IsPathWithin(invalidPath!, @"C:\Media"); + + // Assert + Assert.False(result); + _mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void IsPathWithin_WhenParentPathIsNotValid_ShouldReturnFalseWithoutCallingTheStrategy(string? invalidParentPath) + { + // Act + bool result = _sut.IsPathWithin(@"C:\Media\Books\book.epub", invalidParentPath!); + + // Assert + Assert.False(result); + _mockPathStrategy.DidNotReceive().IsPathWithin(Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index ee30f141..d28c8c98 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -120,7 +120,7 @@ public class UnixPathStrategyTests } [Fact] - public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrue() + public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue() { // Arrange string existingPath = "/home/user/existing_file.txt"; @@ -138,7 +138,7 @@ public class UnixPathStrategyTests } [Fact] - public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalse() + public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse() { // Arrange string existingPath = "/home/user/existing_file.txt"; @@ -596,4 +596,42 @@ public class UnixPathStrategyTests Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + + [Theory] + [InlineData("/media/books", "/media/books/book.epub")] // direct child + [InlineData("/media", "/media/books/book.epub")] // nested descendant + [InlineData("/media/books/", "/media/books/book.epub")] // trailing separator on the parent + [InlineData("/media/books", "/media/books/sub/../book.epub")] // relative segments that stay inside + public void IsPathWithin_WithContainedPaths_ShouldReturnTrue(string parentPath, string path) + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + + // Act + bool result = _sut.IsPathWithin(pathId, parentPathId); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("/media/books", "/media/book.epub")] // sibling directory + [InlineData("/media/books", "/Media/Books/book.epub")] // Unix paths are case-sensitive + [InlineData("/media/books", "/media/other/book.epub")] // sibling directory + [InlineData("/media/books", "/media/books/../other/book.epub")] // relative segment that escapes the parent + [InlineData("/media/books", "/etc/passwd")] // unrelated location + [InlineData("/media", "/media")] // the parent itself is not inside itself + public void IsPathWithin_WithPathsOutsideTheParent_ShouldReturnFalse(string parentPath, string path) + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + + // Act + bool result = _sut.IsPathWithin(pathId, parentPathId); + + // Assert + Assert.False(result); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index 1e915b96..9b555d83 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -148,7 +148,7 @@ public class WindowsPathStrategyTests } [Fact] - public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsTrue_ShouldReturnTrue() + public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsTrue_ShouldReturnTrue() { // Arrange string existingPath = @"C:\Users\User\existing_file.txt"; @@ -165,7 +165,7 @@ public class WindowsPathStrategyTests } [Fact] - public void Exists_WhenPathExistsAndIsHiddenAndIncludeHiddenElementsIsFalse_ShouldReturnFalse() + public void Exists_WhenPathExistsAndIsHiddenAndShouldIncludeHiddenElementsIsFalse_ShouldReturnFalse() { // Arrange string existingPath = @"C:\Users\User\existing_file.txt"; @@ -811,4 +811,44 @@ public class WindowsPathStrategyTests Assert.True(result.IsFailure); Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); } + + [Theory] + [InlineData(@"C:\Media\Books", @"C:\Media\Books\book.epub")] // direct child + [InlineData(@"C:\Media", @"C:\Media\Books\book.epub")] // nested descendant + [InlineData(@"C:\Media\Books\", @"C:\Media\Books\book.epub")] // trailing separator on the parent + [InlineData(@"C:\Media\Books", @"c:\media\books\book.epub")] // Windows paths are case-insensitive + [InlineData(@"C:\Media\Books", @"C:\Media\Books\Sub\..\book.epub")] // relative segments that stay inside + public void IsPathWithin_WithContainedPaths_ShouldReturnTrue(string parentPath, string path) + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + + // Act + bool result = _sut.IsPathWithin(pathId, parentPathId); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(@"C:\Media\Books", @"C:\Media\book.epub")] // sibling directory + [InlineData(@"C:\Media\Books", @"D:\Media\Books\book.epub")] // different drive + [InlineData(@"C:\Media\Books", @"C:\Media\BookShelf\book.epub")] // a sibling whose name shares the prefix + [InlineData(@"C:\Media\Books", @"C:\Media\Other\book.epub")] // sibling directory + [InlineData(@"C:\Media\Books", @"C:\Media\Books\..\Other\book.epub")] // relative segment that escapes the parent + [InlineData(@"C:\Media\Books", @"C:\Windows\System32\config\SAM")] // unrelated location + [InlineData(@"C:\Media", @"C:\Media")] // the parent itself is not inside itself + public void IsPathWithin_WithPathsOutsideTheParent_ShouldReturnFalse(string parentPath, string path) + { + // Arrange + FileSystemPathId parentPathId = _fileSystemPathIdFixture.Create(parentPath); + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path); + + // Act + bool result = _sut.IsPathWithin(pathId, parentPathId); + + // Assert + Assert.False(result); + } } 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 e6e9d88e..0a6d35fa 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 @@ -59,7 +59,8 @@ public class LibraryTests Assert.Equal(title, result.Value.Title); Assert.Equal(libraryType, result.Value.LibraryType); Assert.Equal(2, result.Value.ContentLocations.Count); - Assert.Equal(coverImageSourcePath, result.Value.CoverImage); + Assert.True(result.Value.CoverImage.HasValue); + Assert.Equal(coverImageSourcePath, result.Value.CoverImage.Value); Assert.False(result.Value.IsEnabled); Assert.True(result.Value.IsLocked); Assert.False(result.Value.CanDownloadMetadataFromWeb); @@ -82,7 +83,7 @@ public class LibraryTests "My Library", LibraryType.Movie, ["C:/Media"], - null, + Optional.None(), isEnabled: true, isLocked: false, canDownloadMetadataFromWeb: true, @@ -108,7 +109,7 @@ public class LibraryTests "My Library", LibraryType.Book, [""], - null, + Optional.None(), isEnabled: true, isLocked: false, canDownloadMetadataFromWeb: true, @@ -128,10 +129,10 @@ public class LibraryTests Library library = _libraryFixture.Create(); // Act - string? coverImageSourcePath = library.CoverImageSourcePath; + Optional coverImageSourcePath = library.CoverImageSourcePath; // Assert - Assert.Null(coverImageSourcePath); + Assert.False(coverImageSourcePath.HasValue); } [Fact] @@ -143,7 +144,7 @@ public class LibraryTests "My Library", LibraryType.Book, ["C:/Media/Books", "D:/Books"], - null, + Optional.None(), isEnabled: true, isLocked: false, canDownloadMetadataFromWeb: true, @@ -170,7 +171,7 @@ public class LibraryTests "My Library", LibraryType.Book, [contentLocation!], - null, + Optional.None(), isEnabled: true, isLocked: false, canDownloadMetadataFromWeb: true, @@ -260,6 +261,7 @@ public class LibraryTests library.SetInternalLibraryCoverImagePath(internalPath); // Assert - Assert.Equal(internalPath, library.CoverImage); + Assert.True(library.CoverImage.HasValue); + Assert.Equal(internalPath, library.CoverImage.Value); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs index 1373e818..c79c4ee9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs @@ -45,18 +45,19 @@ public class LibraryScanFailedDomainEventTests Assert.Equal(libraryId, domainEvent.LibraryId); Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId); Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); - Assert.Equal(errorMessage, domainEvent.ErrorMessage); + Assert.True(domainEvent.ErrorMessage.HasValue); + Assert.Equal(errorMessage, domainEvent.ErrorMessage.Value); Assert.IsType(domainEvent, exactMatch: false); } [Fact] - public void Constructor_WhenCalledWithoutErrorMessage_ShouldDefaultErrorMessageToNull() + public void Constructor_WhenCalledWithoutErrorMessage_ShouldLeaveErrorMessageUnset() { // Act LibraryScanFailedDomainEvent domainEvent = _libraryScanFailedDomainEventFixture.Create(includeErrorMessage: false); // Assert - Assert.Null(domainEvent.ErrorMessage); + Assert.False(domainEvent.ErrorMessage.HasValue); Assert.IsType(domainEvent, exactMatch: false); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs deleted file mode 100644 index d7e7bac7..00000000 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs +++ /dev/null @@ -1,84 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Errors; -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; -using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorRoleTests -{ - private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new(); - - [Fact] - public void Create_WhenCalledWithDisplayNameAndCategory_ShouldCreateRole() - { - // Act - Result result = MediaContributorRole.Create("Author", MediaContributorRoleCategory.Author); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal("Author", result.Value.DisplayName); - Assert.Equal(MediaContributorRoleCategory.Author, result.Value.Category); - } - - [Fact] - public void Create_WhenCalledWithEmptyDisplayName_ShouldReturnError() - { - // Act - Result result = MediaContributorRole.Create(" ", MediaContributorRoleCategory.Author); - - // Assert - Assert.True(result.IsFailure); - Assert.Equal(Errors.MediaContributors.MediaContributorRoleNameCannotBeEmpty, result.FirstError); - } - - [Fact] - public void Equals_WithSameValues_ShouldReturnTrue() - { - // Arrange - MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); - MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); - - // Act - bool result = firstRole.Equals(secondRole); - - // Assert - Assert.True(result); - } - - [Fact] - public void Equals_WithDifferentDisplayName_ShouldReturnFalse() - { - // Arrange - MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); - MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Writer", category: MediaContributorRoleCategory.Author); - - // Act - bool result = firstRole.Equals(secondRole); - - // Assert - Assert.False(result); - } - - [Fact] - public void Equals_WithDifferentCategory_ShouldReturnFalse() - { - // Arrange - MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Author); - MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Author", category: MediaContributorRoleCategory.Translator); - - // Act - bool result = firstRole.Equals(secondRole); - - // Assert - Assert.False(result); - } -} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs index c855ebe0..4974e9b1 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs @@ -4,7 +4,6 @@ using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -58,26 +57,6 @@ public class VideoMetadataTests Assert.False(result.Value.OriginalLanguage.HasValue); } - [Fact] - public void Create_WhenResolutionIsNull_ShouldThrowArgumentNullException() - { - // Act & Assert - Assert.Throws(() => VideoMetadata.Create( - "Inception", - Optional.None(), - durationInSeconds: 8880, - null!, - Optional.None(), - _releaseInfoFixture.Create(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - Optional.None(), - [], - [])); - } - [Fact] public void Equals_WithSameValues_ShouldReturnTrue() { 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 6bb62492..14b6bd6d 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,9 +1,10 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; -using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.MediaContributorBoundedContext.MediaContributorAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -18,7 +19,6 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoun public class BookTests { private readonly BookFixture _bookFixture = new(); - private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); [Fact] public void Create_WhenCalledWithValidData_ShouldCreateBook() @@ -38,16 +38,16 @@ public class BookTests { // Arrange Book book = _bookFixture.Create(); - MediaContributorId firstContributorId = _mediaContributorIdFixture.Create(); - MediaContributorId secondContributorId = _mediaContributorIdFixture.Create(); + BookMediaContributor firstContributor = CreateAuthorContributor(); + BookMediaContributor secondContributor = CreateAuthorContributor(); // Act - book.UpdateContributors([firstContributorId, secondContributorId]); + book.UpdateContributors([firstContributor, secondContributor]); // Assert Assert.Equal(2, book.Contributors.Count); - Assert.Contains(book.Contributors, contributorId => contributorId == firstContributorId); - Assert.Contains(book.Contributors, contributorId => contributorId == secondContributorId); + Assert.Contains(book.Contributors, contributor => contributor == firstContributor); + Assert.Contains(book.Contributors, contributor => contributor == secondContributor); } [Fact] @@ -55,16 +55,45 @@ public class BookTests { // Arrange Book book = _bookFixture.Create(); - book.UpdateContributors([_mediaContributorIdFixture.Create()]); - MediaContributorId replacementContributorId = _mediaContributorIdFixture.Create(); + book.UpdateContributors([CreateAuthorContributor()]); + BookMediaContributor replacementContributor = CreateAuthorContributor(); // Act - book.UpdateContributors([replacementContributorId]); + book.UpdateContributors([replacementContributor]); // Assert // the previous contributors are replaced, not appended - MediaContributorId contributorId = Assert.Single(book.Contributors); - Assert.Equal(replacementContributorId, contributorId); + BookMediaContributor contributor = Assert.Single(book.Contributors); + Assert.Equal(replacementContributor, contributor); + } + + [Fact] + public void Create_WhenContributorsContainDuplicates_ShouldKeepOnlyUniqueContributors() + { + // Arrange + BookMediaContributor contributor = CreateAuthorContributor(); + + // Act + Book book = _bookFixture.Create(contributors: [contributor, contributor]); + + // Assert + BookMediaContributor storedContributor = Assert.Single(book.Contributors); + Assert.Equal(contributor, storedContributor); + } + + [Fact] + public void UpdateContributors_WhenCalledWithDuplicates_ShouldKeepOnlyUniqueContributors() + { + // Arrange + Book book = _bookFixture.Create(); + BookMediaContributor contributor = CreateAuthorContributor(); + + // Act + book.UpdateContributors([contributor, contributor]); + + // Assert + BookMediaContributor storedContributor = Assert.Single(book.Contributors); + Assert.Equal(contributor, storedContributor); } [Fact] @@ -107,7 +136,7 @@ public class BookTests Assert.Equal(sourceBook.Path, book.Path); Assert.Equal(sourceBook.Metadata, book.Metadata); Assert.Equal(createdOnUtc, book.CreatedOnUtc); - Assert.Equal(updatedOnUtc, book.UpdatedOnUtc); + Assert.Equal(Optional.Some(updatedOnUtc), book.UpdatedOnUtc); Assert.Equal(sourceBook.ISBNs, book.ISBNs); Assert.Equal(sourceBook.Ratings, book.Ratings); } @@ -229,4 +258,13 @@ public class BookTests Assert.False(hasMetadataProvider); Assert.False(hasCoverImagePath); } + + /// + /// Creates a of a random media contributor playing the Author role. + /// + /// The created . + private static BookMediaContributor CreateAuthorContributor() + { + return BookMediaContributor.Create(MediaContributorId.CreateUnique(), MediaContributorRole.Author).Value; + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs deleted file mode 100644 index 60e8122d..00000000 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class BookLibraryServiceTests -{ - [Fact] - public void Books_WhenAccessed_ShouldThrowNotImplementedException() - { - // Arrange - BookLibraryService sut = new(); - - // Act & Assert - Assert.Throws(() => sut.Books); - } -} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs deleted file mode 100644 index 6eed5bbe..00000000 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class BookLibraryIdTests -{ - private readonly BookLibraryIdFixture _bookLibraryIdFixture = new(); - - [Fact] - public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() - { - // Act - Result result = BookLibraryId.CreateUnique(); - - // Assert - Assert.False(result.IsFailure); - Assert.NotEqual(default, result.Value.Value); - } - - [Fact] - public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() - { - // Arrange - Guid value = Guid.NewGuid(); - - // Act - Result result = BookLibraryId.Create(value); - - // Assert - Assert.False(result.IsFailure); - Assert.Equal(value, result.Value.Value); - } - - [Fact] - public void Equals_WithSameValue_ShouldReturnTrue() - { - // Arrange - Guid value = Guid.NewGuid(); - BookLibraryId firstId = _bookLibraryIdFixture.Create(value); - BookLibraryId secondId = _bookLibraryIdFixture.Create(value); - - // Act - bool result = firstId.Equals(secondId); - - // Assert - Assert.True(result); - } - - [Fact] - public void Equals_WithDifferentValue_ShouldReturnFalse() - { - // Arrange - BookLibraryId firstId = _bookLibraryIdFixture.Create(); - BookLibraryId secondId = _bookLibraryIdFixture.Create(); - - // Act - bool result = firstId.Equals(secondId); - - // Assert - Assert.False(result); - } -} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs index 1c2a7799..bd9cf7e2 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs @@ -48,7 +48,7 @@ public class IsbnTests public void Create_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value) { // Act - Result result = Isbn.Create(value, IsbnFormat.Isbn10); + Result result = Isbn.Create(value!, IsbnFormat.Isbn10); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index c5a2ade0..99208074 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -40,6 +40,7 @@ public class AuthorizationServiceTests public AuthorizationServiceTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockAuthorizationPolicyFactory = Substitute.For(); @@ -53,7 +54,7 @@ public class AuthorizationServiceTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -61,7 +62,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -70,7 +71,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -78,7 +79,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -88,7 +89,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanViewUsers]); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -96,7 +97,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -111,7 +112,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -119,7 +120,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -128,7 +129,7 @@ public class AuthorizationServiceTests // Arrange UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -136,7 +137,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -146,7 +147,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanDeleteUsers]); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -154,7 +155,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -170,7 +171,7 @@ public class AuthorizationServiceTests directPermissions: [AuthorizationPermission.CanViewUsers], rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -178,7 +179,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -186,7 +187,7 @@ public class AuthorizationServiceTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -194,7 +195,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -203,7 +204,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -211,7 +212,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -226,7 +227,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -234,7 +235,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -249,7 +250,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -257,7 +258,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -266,7 +267,7 @@ public class AuthorizationServiceTests // Arrange UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -274,7 +275,7 @@ public class AuthorizationServiceTests // Assert Assert.False(result); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -409,7 +410,7 @@ public class AuthorizationServiceTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -418,7 +419,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -427,7 +428,7 @@ public class AuthorizationServiceTests // Arrange Guid userId = Guid.NewGuid(); Error error = Error.Failure("Database.Error", "Failed to retrieve user"); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(error); // Act @@ -436,7 +437,7 @@ public class AuthorizationServiceTests // Assert Assert.True(result.IsFailure); Assert.Equal(error, result.FirstError); - await _mockUserRepository.Received(1).GetByIdAsync(userId, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); } [Fact] @@ -444,7 +445,7 @@ public class AuthorizationServiceTests { // Arrange UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -455,7 +456,7 @@ public class AuthorizationServiceTests Assert.Equal(user.Id, result.Value.UserId); Assert.Null(result.Value.Role); Assert.Empty(result.Value.Permissions); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -469,7 +470,7 @@ public class AuthorizationServiceTests AuthorizationPermission.CanDeleteUsers ]); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -481,7 +482,7 @@ public class AuthorizationServiceTests Assert.Null(result.Value.Role); Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers], result.Value.Permissions); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -499,7 +500,7 @@ public class AuthorizationServiceTests UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -511,7 +512,7 @@ public class AuthorizationServiceTests Assert.Equal("Admin", result.Value.Role); Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers], result.Value.Permissions); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } [Fact] @@ -530,7 +531,7 @@ public class AuthorizationServiceTests directPermissions: [AuthorizationPermission.CanRegisterUsers], rolePermissions: rolePermissions); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -549,6 +550,6 @@ public class AuthorizationServiceTests }, result.Value.Permissions ); - await _mockUserRepository.Received(1).GetByIdAsync(user.Id, Arg.Any()); + await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs index 352f2f8b..022605c9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs @@ -40,6 +40,7 @@ public class LibraryOwnershipPolicyTests public LibraryOwnershipPolicyTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); @@ -59,8 +60,8 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -69,7 +70,7 @@ public class LibraryOwnershipPolicyTests // Arrange Guid userId = Guid.NewGuid(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -77,7 +78,7 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -86,7 +87,7 @@ public class LibraryOwnershipPolicyTests // Arrange Guid userId = Guid.NewGuid(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve user")); // Act @@ -94,7 +95,7 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -107,7 +108,7 @@ public class LibraryOwnershipPolicyTests { "Admin", [] } }); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(adminUser.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(adminUser.Id, cancellationToken: Arg.Any()) .Returns(Result.From(adminUser)); // Act @@ -115,7 +116,7 @@ public class LibraryOwnershipPolicyTests // Assert Assert.True(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -125,9 +126,9 @@ public class LibraryOwnershipPolicyTests Guid userId = Guid.NewGuid(); UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act @@ -144,9 +145,9 @@ public class LibraryOwnershipPolicyTests Guid userId = Guid.NewGuid(); UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve library")); // Act @@ -164,9 +165,9 @@ public class LibraryOwnershipPolicyTests UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryEntity library = _libraryEntityFixture.Create(userId: userId); LibraryOwnershipPolicyContext context = new(library.Id); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act @@ -184,9 +185,9 @@ public class LibraryOwnershipPolicyTests UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryEntity library = _libraryEntityFixture.Create(userId: Guid.NewGuid()); LibraryOwnershipPolicyContext context = new(library.Id); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) .Returns(Result.From(library)); // Act diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs index e21aec33..81eb3640 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs @@ -32,6 +32,7 @@ public class Over18PolicyTests public Over18PolicyTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); @@ -43,7 +44,7 @@ public class Over18PolicyTests { // Arrange UserEntity user = _userEntityFixture.Create(); - _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + _mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any()) .Returns(Result.From(user)); // Act @@ -58,7 +59,7 @@ public class Over18PolicyTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -73,7 +74,7 @@ public class Over18PolicyTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve user")); // Act @@ -88,7 +89,7 @@ public class Over18PolicyTests { // Arrange Guid userId = Guid.NewGuid(); - _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.Success(null)); // Act 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 0a23ca9f..5a2e3bc1 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 @@ -2,7 +2,7 @@ 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.Books; +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; @@ -139,7 +139,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests "Test Title", Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); Assert.Equal(0, coverArtwork.Ordinal); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); @@ -168,7 +168,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests 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.BookArtwork = [_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))]; + 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" })); @@ -179,7 +179,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // 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.BookArtwork); + 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); @@ -212,7 +212,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert await mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkType.Cover, coverArtwork.ArtworkType); Assert.Equal(0, coverArtwork.Ordinal); Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); @@ -226,7 +226,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Arrange _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -330,7 +330,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: false))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -346,7 +346,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -354,7 +354,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // 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.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("Local Provider", coverArtwork.Provider); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -377,7 +377,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -405,7 +405,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -429,7 +429,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + 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()) @@ -440,7 +440,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -465,7 +465,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.BookArtwork = [_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))]; + 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" })); @@ -474,7 +474,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + 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); @@ -507,7 +507,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Failed, coverArtwork.Status); Assert.Null(coverArtwork.FileName); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -532,7 +532,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests SetupRealServiceProvider(artworkPluginId, artworkProvider, mockBookArtworkService, mockFileHashService); BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); - book.BookArtwork = [_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))]; + 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" })); @@ -541,7 +541,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + 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); @@ -577,7 +577,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // 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.BookArtwork); + 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); @@ -605,7 +605,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests 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.BookArtwork = [_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))]; + 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()) @@ -623,7 +623,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests "Test Title", Arg.Any(), Arg.Any()); - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + 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); @@ -669,7 +669,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -682,7 +682,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -691,7 +691,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Assert // a failing artwork provider must not prevent the artwork of the other provider from being used - BookArtworkEntity coverArtwork = Assert.Single(book.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("Second Provider", coverArtwork.Provider); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -735,7 +735,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -748,7 +748,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any()) .Returns(Result.From>(new Dictionary { [book.Id] = "Frank Herbert" })); @@ -757,7 +757,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // 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.BookArtwork); + BookArtworkEntity coverArtwork = Assert.Single(book.Artwork); Assert.Equal(ArtworkStatus.Enriched, coverArtwork.Status); Assert.Equal("Second Provider", coverArtwork.Provider); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); @@ -769,7 +769,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests // Arrange _mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); IMediaLibraryScanJob mockChildJob = Substitute.For(); mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -815,7 +815,7 @@ public class MediaLibraryScanArtworkEnrichmentJobTests private void SetupSingleBookPage(BookEntity book, Guid artworkPluginId) { ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -827,6 +827,6 @@ public class MediaLibraryScanArtworkEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs index 8b60619f..d9b0fd19 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs @@ -55,6 +55,7 @@ public class MediaLibraryScanDiffJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs index 8fb60013..8630e88d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs @@ -62,6 +62,7 @@ public class MediaLibraryScanHashJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); 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 01776927..d315fb11 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 @@ -4,7 +4,7 @@ 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.Books; +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; @@ -127,7 +127,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .Returns(Result.From(0)); _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -144,7 +144,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Arrange _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -339,8 +339,8 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); - MediaContributorDto translator = _mediaContributorDtoFixture.Create(displayName: "Jane Translator", roleName: "Translator", roleCategory: MediaContributorRoleCategory.Translator); + 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])); @@ -362,15 +362,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests 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 role and the category of each contributor - Assert.Equal(2, book.BookContributors.Count); - BookContributorEntity linkedAuthor = Assert.Single(book.BookContributors, contributor => contributor.MediaContributorId == authorEntity.Id); - Assert.Equal("Author", linkedAuthor.RoleName); - Assert.Equal(MediaContributorRoleCategory.Author, linkedAuthor.RoleCategory); + // 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.BookContributors, contributor => contributor.MediaContributorId == translatorEntity.Id); - Assert.Equal("Translator", linkedTranslator.RoleName); - Assert.Equal(MediaContributorRoleCategory.Translator, linkedTranslator.RoleCategory); + BookContributorEntity linkedTranslator = Assert.Single(book.Contributors, contributor => contributor.MediaContributorId == translatorEntity.Id); + Assert.Equal(MediaContributorRole.Translator, linkedTranslator.Role); Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); } @@ -382,7 +380,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); @@ -396,7 +394,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); MediaContributorEntity authorEntity = _mediaContributorEntityFixture.Create(displayName: "Frank Herbert"); _mockMediaContributorRepository.FindOrCreateByDisplayNameAsync("Frank Herbert", Arg.Any(), Arg.Any()) @@ -408,10 +406,10 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // 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.BookContributors); - Assert.Single(secondBook.BookContributors); - Assert.Equal(authorEntity.Id, firstBook.BookContributors[0].MediaContributorId); - Assert.Equal(authorEntity.Id, secondBook.BookContributors[0].MediaContributorId); + 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] @@ -435,7 +433,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -473,7 +471,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); ILibraryRepository mockLibraryRepository = Substitute.For(); - mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true))); _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); @@ -503,7 +501,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -528,7 +526,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -607,7 +605,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(roleName: "Author", roleCategory: MediaContributorRoleCategory.Author) with { Name = null }; + MediaContributorDto namelessContributor = _mediaContributorDtoFixture.Create(role: MediaContributorRole.Author) with { Name = null }; firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [namelessContributor])); @@ -621,7 +619,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // 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.BookContributors); + Assert.Empty(book.Contributors); Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus); Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); } @@ -650,9 +648,9 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); // Assert - BookContributorEntity linkedContributor = Assert.Single(book.BookContributors); - Assert.Equal("Contributor", linkedContributor.RoleName); - Assert.Equal(MediaContributorRoleCategory.Other, linkedContributor.RoleCategory); + // 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); } @@ -665,7 +663,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests IMetadataProvider firstProvider = Substitute.For(); firstProvider.Name.Returns("First Provider"); firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); - MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", roleName: "Author", roleCategory: MediaContributorRoleCategory.Author); + MediaContributorDto author = _mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author); firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) .Returns(_bookMetadataDtoFixture.Create(title: "First Title", contributors: [author])); @@ -689,7 +687,7 @@ public class MediaLibraryScanMetadataEnrichmentJobTests // Arrange _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); IMediaLibraryScanJob mockChildJob = Substitute.For(); mockChildJob.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -747,6 +745,6 @@ public class MediaLibraryScanMetadataEnrichmentJobTests .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(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); } } 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 ff984873..84ef1735 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 @@ -2,7 +2,7 @@ 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.Books; +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.Repositories.Users; @@ -219,7 +219,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to get the media library")); SetupConfigurations(); @@ -254,7 +254,7 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -413,10 +413,10 @@ public class MediaLibraryScanProviderConfigurationInvalidationJobTests /// The artwork provider configurations of the media library. private void SetupLibraryAndConfigurations(LibraryEntity library, List? metadataConfigurations = null, List? artworkConfigurations = null) { - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(library)); SetupConfigurations(metadataConfigurations, artworkConfigurations); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); } /// 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 7704dc1a..ccc0f5ee 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,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Books; +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; @@ -106,7 +106,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(null)); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -133,7 +133,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -158,7 +158,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From>(["existing.pdf"])); _mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any()) .Returns(Result.From(_bookEntityFixture.Create(path: "existing.pdf"))); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); @@ -356,7 +356,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(Result.Updated)); _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) .Returns(Result.From>([])); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); IMediaLibraryScanJob mockChild = Substitute.For(); mockChild.ExecuteAsync(Arg.Any(), Arg.Any(), Arg.Any()) @@ -389,7 +389,7 @@ public class MediaLibraryScanResultsSaveJobTests .Returns(Result.From(null)); _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Created)); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); // Act await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs deleted file mode 100644 index ccca888c..00000000 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs +++ /dev/null @@ -1,333 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -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.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.Common; -using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; - -/// -/// Contains unit tests for the class. -/// -[ExcludeFromCodeCoverage] -public class MetadataAggregatorTests -{ - private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); - private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); - private readonly IsbnDtoFixture _isbnDtoFixture = new(); - private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); - private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); - private readonly GenreDtoFixture _genreDtoFixture = new(); - private readonly TagDtoFixture _tagDtoFixture = new(); - private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); - - [Fact] - public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, - title: "First Title", - originalTitle: "First Original Title", - description: "First Description", - publisher: "First Publisher", - pageCount: 100, - format: BookFormat.Hardcover, - edition: "First Edition", - volumeNumber: 1, - asin: "FIRST-ASIN", - goodreadsId: "FIRST-GOODREADS", - lccn: "FIRST-LCCN", - oclcNumber: "FIRST-OCLC", - openLibraryId: "FIRST-OL", - libraryThingId: "FIRST-LT", - googleBooksId: "FIRST-GOOGLE", - barnesAndNobleId: "FIRST-BN", - appleBooksId: "FIRST-APPLE", - coverImagePath: "First Cover"); - BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, - title: "Second Title", - originalTitle: "Second Original Title", - description: "Second Description", - publisher: "Second Publisher", - pageCount: 200, - format: BookFormat.Paperback, - edition: "Second Edition", - volumeNumber: 2, - asin: "SECOND-ASIN", - goodreadsId: "SECOND-GOODREADS", - lccn: "SECOND-LCCN", - oclcNumber: "SECOND-OCLC", - openLibraryId: "SECOND-OL", - libraryThingId: "SECOND-LT", - googleBooksId: "SECOND-GOOGLE", - barnesAndNobleId: "SECOND-BN", - appleBooksId: "SECOND-APPLE", - coverImagePath: "First Cover"); - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal("First Title", result.Title); - Assert.Equal("First Original Title", result.OriginalTitle); - Assert.Equal("First Description", result.Description); - Assert.Equal("First Publisher", result.Publisher); - Assert.Equal(100, result.PageCount); - Assert.Equal(BookFormat.Hardcover, result.Format); - Assert.Equal("First Edition", result.Edition); - Assert.Equal(1, result.VolumeNumber); - Assert.Equal("FIRST-ASIN", result.ASIN); - Assert.Equal("FIRST-GOODREADS", result.GoodreadsId); - Assert.Equal("FIRST-LCCN", result.LCCN); - Assert.Equal("FIRST-OCLC", result.OCLCNumber); - Assert.Equal("FIRST-OL", result.OpenLibraryId); - Assert.Equal("FIRST-LT", result.LibraryThingId); - Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId); - Assert.Equal("FIRST-BN", result.BarnesAndNobleId); - Assert.Equal("FIRST-APPLE", result.AppleBooksId); - Assert.Equal("First Cover", result.CoverImagePath); - } - - [Fact] - public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, description: null, publisher: null, pageCount: null); - BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: "Second Title", description: "Second Description", publisher: "Second Publisher", pageCount: 200); - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal("Second Title", result.Title); - Assert.Equal("Second Description", result.Description); - Assert.Equal("Second Publisher", result.Publisher); - Assert.Equal(200, result.PageCount); - } - - [Fact] - public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null); - BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null); - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Null(result.Title); - Assert.Null(result.Description); - Assert.Null(result.Publisher); - Assert.Null(result.PageCount); - Assert.Null(result.Format); - Assert.Null(result.Edition); - Assert.Null(result.VolumeNumber); - Assert.Null(result.Series); - } - - [Fact] - public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false); - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false); - first = first with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: ReleaseCountry.US) }; - second = second with { ReleaseInfo = _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: ReleaseCountry.GB, releaseVersion: "2.0") }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); - Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear); - Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate); - Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear); - Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); - Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion); - } - - [Fact] - public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001) }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); - } - - [Fact] - public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Null(result.ReleaseInfo); - } - - [Fact] - public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")] }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")] }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(3, result.Genres!.Count); - Assert.Contains(result.Genres, genre => genre.Name == "Science fiction"); - Assert.Contains(result.Genres, genre => genre.Name == "Space opera"); - Assert.Contains(result.Genres, genre => genre.Name == "Fantasy"); - } - - [Fact] - public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")] }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")] }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(3, result.Tags!.Count); - Assert.Contains(result.Tags, tag => tag.Name == "Tag A"); - Assert.Contains(result.Tags, tag => tag.Name == "Tag B"); - Assert.Contains(result.Tags, tag => tag.Name == "Tag C"); - } - - [Fact] - public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)] }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)] }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(2, result.Isbns!.Count); - Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157"); - Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152"); - } - - [Fact] - public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")] }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author"), _mediaContributorDtoFixture.Create("Translator B", "Translator")] }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(2, result.Contributors!.Count); - Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A"); - Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B"); - } - - [Fact] - public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal(2, result.Ratings!.Count); - Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre); - Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary); - } - - [Fact] - public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A")], Genres = [_genreDtoFixture.Create(name: "Genre A")], Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal("Tag A", Assert.Single(result.Tags!).Name); - Assert.Equal("Genre A", Assert.Single(result.Genres!).Name); - Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value); - Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName); - Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source); - } - - [Fact] - public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag B")], Genres = [_genreDtoFixture.Create(name: "Genre B")], Isbns = [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)], Contributors = [_mediaContributorDtoFixture.Create("Author B", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal("Tag B", Assert.Single(result.Tags!).Name); - Assert.Equal("Genre B", Assert.Single(result.Genres!).Name); - Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value); - Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName); - Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source); - } - - [Fact] - public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Null(result.Genres); - Assert.Null(result.Tags); - Assert.Null(result.Isbns); - Assert.Null(result.Contributors); - Assert.Null(result.Ratings); - } - - [Fact] - public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage() - { - // Arrange - BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English") }; - BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch") }; - - // Act - BookMetadataDto result = MetadataAggregator.Merge(first, second); - - // Assert - Assert.Equal("en", result.Language!.LanguageCode); - } -} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs index 9b59314d..d85f999b 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs @@ -60,7 +60,7 @@ public class ScanFailurePublisherTests Arg.Is(domainEvent => domainEvent.LibraryId == libraryId && domainEvent.MediaLibraryScanCompositeId == compositeId - && domainEvent.ErrorMessage == "The scan job failed"), + && domainEvent.ErrorMessage.HasValue && domainEvent.ErrorMessage.Value == "The scan job failed"), Arg.Any()); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs index fae7f289..665e6cd0 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -58,6 +58,7 @@ public class BooksFileSystemDiscoveryJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLibraryRepository = Substitute.For(); _mockStagingResultsRepository = Substitute.For(); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); @@ -84,7 +85,7 @@ public class BooksFileSystemDiscoveryJobTests public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); // Act @@ -103,7 +104,7 @@ public class BooksFileSystemDiscoveryJobTests public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() { // Arrange - _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Metadata/MetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Metadata/MetadataAggregatorTests.cs new file mode 100644 index 00000000..4a80ac70 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Metadata/MetadataAggregatorTests.cs @@ -0,0 +1,583 @@ +#region ========================================================================= USING ===================================================================================== +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.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MetadataAggregatorTests +{ + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + title: "First Title", + originalTitle: "First Original Title", + description: "First Description", + publisher: "First Publisher", + pageCount: 100, + format: BookFormat.Hardcover, + edition: "First Edition", + volumeNumber: 1, + asin: "FIRST-ASIN", + goodreadsId: "FIRST-GOODREADS", + lccn: "FIRST-LCCN", + oclcNumber: "FIRST-OCLC", + openLibraryId: "FIRST-OL", + libraryThingId: "FIRST-LT", + googleBooksId: "FIRST-GOOGLE", + barnesAndNobleId: "FIRST-BN", + appleBooksId: "FIRST-APPLE", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + title: "Second Title", + originalTitle: "Second Original Title", + description: "Second Description", + publisher: "Second Publisher", + pageCount: 200, + format: BookFormat.Paperback, + edition: "Second Edition", + volumeNumber: 2, + asin: "SECOND-ASIN", + goodreadsId: "SECOND-GOODREADS", + lccn: "SECOND-LCCN", + oclcNumber: "SECOND-OCLC", + openLibraryId: "SECOND-OL", + libraryThingId: "SECOND-LT", + googleBooksId: "SECOND-GOOGLE", + barnesAndNobleId: "SECOND-BN", + appleBooksId: "SECOND-APPLE", + coverImagePath: "First Cover"); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First Title", result.Title); + Assert.Equal("First Original Title", result.OriginalTitle); + Assert.Equal("First Description", result.Description); + Assert.Equal("First Publisher", result.Publisher); + Assert.Equal(100, result.PageCount); + Assert.Equal(BookFormat.Hardcover, result.Format); + Assert.Equal("First Edition", result.Edition); + Assert.Equal(1, result.VolumeNumber); + Assert.Equal("FIRST-ASIN", result.ASIN); + Assert.Equal("FIRST-GOODREADS", result.GoodreadsId); + Assert.Equal("FIRST-LCCN", result.LCCN); + Assert.Equal("FIRST-OCLC", result.OCLCNumber); + Assert.Equal("FIRST-OL", result.OpenLibraryId); + Assert.Equal("FIRST-LT", result.LibraryThingId); + Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId); + Assert.Equal("FIRST-BN", result.BarnesAndNobleId); + Assert.Equal("FIRST-APPLE", result.AppleBooksId); + Assert.Equal("First Cover", result.CoverImagePath); + } + + [Fact] + public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeTitle: false, + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: null, + description: null, + publisher: null, + pageCount: null); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Second Title", + description: "Second Description", + publisher: "Second Publisher", + pageCount: 200); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Second Title", result.Title); + Assert.Equal("Second Description", result.Description); + Assert.Equal("Second Publisher", result.Publisher); + Assert.Equal(200, result.PageCount); + } + + [Fact] + public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeTitle: false, + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: null, + coverImagePath: null); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeTitle: false, + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: null, + coverImagePath: null); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Description); + Assert.Null(result.Publisher); + Assert.Null(result.PageCount); + Assert.Null(result.Format); + Assert.Null(result.Edition); + Assert.Null(result.VolumeNumber); + Assert.Null(result.Series); + } + + [Fact] + public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: ReleaseCountry.US)); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: ReleaseCountry.GB, releaseVersion: "2.0")); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate); + Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion); + } + + [Fact] + public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001)); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); + } + + [Fact] + public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + genres: [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")]); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + genres: [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")]); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(3, result.Genres!.Count); + Assert.Contains(result.Genres, genre => genre.Name == "Science fiction"); + Assert.Contains(result.Genres, genre => genre.Name == "Space opera"); + Assert.Contains(result.Genres, genre => genre.Name == "Fantasy"); + } + + [Fact] + public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + tags: [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")]); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + tags: [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")]); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(3, result.Tags!.Count); + Assert.Contains(result.Tags, tag => tag.Name == "Tag A"); + Assert.Contains(result.Tags, tag => tag.Name == "Tag B"); + Assert.Contains(result.Tags, tag => tag.Name == "Tag C"); + } + + [Fact] + public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)]); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)]); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Isbns!.Count); + Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157"); + Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152"); + } + + [Fact] + public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author)]); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author), _mediaContributorDtoFixture.Create("Translator B", MediaContributorRole.Translator)]); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A"); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B"); + } + + [Fact] + public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)]); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)]); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Ratings!.Count); + Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre); + Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary); + } + + [Fact] + public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + tags: [_tagDtoFixture.Create(name: "Tag A")], + genres: [_genreDtoFixture.Create(name: "Genre A")], + isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], + contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author)], + ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)]); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Tag A", Assert.Single(result.Tags!).Name); + Assert.Equal("Genre A", Assert.Single(result.Genres!).Name); + Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value); + Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName); + Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source); + } + + [Fact] + public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + tags: [_tagDtoFixture.Create(name: "Tag B")], + genres: [_genreDtoFixture.Create(name: "Genre B")], + isbns: [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)], + contributors: [_mediaContributorDtoFixture.Create("Author B", MediaContributorRole.Author)], + ratings: [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)]); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Tag B", Assert.Single(result.Tags!).Name); + Assert.Equal("Genre B", Assert.Single(result.Genres!).Name); + Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value); + Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName); + Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source); + } + + [Fact] + public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeLanguage: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover"); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.Genres); + Assert.Null(result.Tags); + Assert.Null(result.Isbns); + Assert.Null(result.Contributors); + Assert.Null(result.Ratings); + } + + [Fact] + public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + language: _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English")); + BookMetadataDto second = _bookMetadataDtoFixture.Create( + includeReleaseInfo: false, + includeGenres: false, + includeTags: false, + includeFormat: false, + includeVolumeNumber: false, + title: "Title", + coverImagePath: "First Cover", + language: _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch")); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("en", result.Language!.LanguageCode); + } +} 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 29bcf855..9b3069b6 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 @@ -58,6 +58,7 @@ public class BookReadingServiceTests _mockPluginManager.GetPlugins().Returns([_mockPlugin]); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository); LibraryBookReaderConfigurationEntity enabledConfiguration = _configurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs index d44a916c..6f31de34 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -45,6 +45,7 @@ public class MediaLibraryProviderConfigurationStoreTests public MediaLibraryProviderConfigurationStoreTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockMetadataConfigurationRepository = Substitute.For(); _mockArtworkConfigurationRepository = Substitute.For(); _mockBookReaderConfigurationRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 864eb16e..ffb41c8d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -62,6 +64,7 @@ public class PluginDetectionSyncJobTests _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockLibraryRepository = Substitute.For(); @@ -187,8 +190,8 @@ public class PluginDetectionSyncJobTests .Returns(Result.From(Result.Updated)); 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(Arg.Any()) - .Returns(Result.From((IEnumerable)[loadedPluginRow, stalePluginRow])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [loadedPluginRow, stalePluginRow], CurrentPage = 1, PerPage = 2, Count = 2, NumberOfPages = 1 })); _mockPluginRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); PluginDetectionSyncJob sut = CreateSut(); @@ -213,8 +216,8 @@ public class PluginDetectionSyncJobTests _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); LibraryEntity bookLibrary = _libraryEntityFixture.Create(libraryType: LibraryType.Book); - _mockLibraryRepository.GetAllAsync(Arg.Any()) - .Returns(Result.From((IEnumerable)[bookLibrary])); + _mockLibraryRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { Data = [bookLibrary], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); PluginDetectionSyncJob sut = CreateSut(); @@ -240,8 +243,8 @@ public class PluginDetectionSyncJobTests assemblyName: "MyPlugin", 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(Arg.Any()) - .Returns(Result.From((IEnumerable)[staleLoadedRow])); + _mockPluginRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Result.From(new PaginatedResultDto { 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/Plugins/PluginSettingsStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs index 2679838f..d181af21 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs @@ -35,6 +35,7 @@ public class PluginSettingsStoreTests public PluginSettingsStoreTests() { _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockPluginRepository = Substitute.For(); _mockLogger = Substitute.For>(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); @@ -49,7 +50,7 @@ public class PluginSettingsStoreTests Guid pluginId = Guid.NewGuid(); Dictionary expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" }; PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, settingsJson: JsonSerializer.Serialize(expectedSettings)); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Result.From(pluginEntity)); // Act @@ -66,7 +67,7 @@ public class PluginSettingsStoreTests // Arrange Guid pluginId = Guid.NewGuid(); PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, includeSettingsJson: false); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Result.From(pluginEntity)); // Act @@ -81,7 +82,7 @@ public class PluginSettingsStoreTests { // Arrange Guid pluginId = Guid.NewGuid(); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Result.From(null)); // Act @@ -96,7 +97,7 @@ public class PluginSettingsStoreTests { // Arrange Guid pluginId = Guid.NewGuid(); - _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + _mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any()) .Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin")); // Act 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 63b116b2..5855411a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/ScheduledJobSchedulerJobTests.cs @@ -4,6 +4,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +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; @@ -73,7 +75,7 @@ public class ScheduledJobSchedulerJobTests _mockScheduledJobExecutionRepository = Substitute.For(); _mockUnitOfWork.ScheduledJobRepository.Returns(_mockScheduledJobRepository); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()).Returns(Result.Updated); @@ -132,7 +134,7 @@ public class ScheduledJobSchedulerJobTests { // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); // Act @@ -152,7 +154,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); // Act @@ -169,7 +171,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); using CancellationTokenSource cycleCancellationTokenSource = new(); _runtimeRegistry.TryStartCycle(scheduledJobId, cycleCancellationTokenSource); @@ -190,7 +192,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob, runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Is(_ => true), Arg.Any())) @@ -213,7 +215,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -233,7 +235,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -252,7 +254,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); // Act ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); @@ -269,7 +271,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); // Act @@ -288,7 +290,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.OnceAtStartup); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); // Act @@ -340,7 +342,7 @@ public class ScheduledJobSchedulerJobTests IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); - mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); _services[typeof(IThemeService)] = mockThemeService; @@ -349,7 +351,7 @@ public class ScheduledJobSchedulerJobTests // Assert mockThemeService.Received(1).GetBundledThemeArchivePaths(); - await mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await mockThemeRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); } [Fact] @@ -391,7 +393,7 @@ public class ScheduledJobSchedulerJobTests IThemeService mockThemeService = Substitute.For(); mockThemeService.GetBundledThemeArchivePaths().Returns([]); IThemeRepository mockThemeRepository = Substitute.For(); - mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); _mockUnitOfWork.ThemeRepository.Returns(mockThemeRepository); _services[typeof(IThemeService)] = mockThemeService; using CancellationTokenSource cancellationTokenSource = new(); @@ -412,7 +414,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(error); // Act await InvokeAsync("RunCycleWorkerAsync", scheduledJobId, false, CancellationToken.None); @@ -428,7 +430,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); @@ -445,7 +447,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); Error error = Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job"); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(error); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(error); // Act await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); @@ -462,7 +464,7 @@ public class ScheduledJobSchedulerJobTests // An interval schedule whose interval is not positive cannot be converted to its domain object. ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(invalidJob); // Act await InvokeAsync("ExecuteScheduledJobRunAsync", scheduledJobId, false, CancellationToken.None); @@ -478,7 +480,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); using CancellationTokenSource cancellationTokenSource = new(); _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) .Do(_ => cancellationTokenSource.Cancel()); @@ -496,7 +498,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("Task.Failed", "The task of the scheduled job failed.")); @@ -515,7 +517,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60)); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromException>(new InvalidOperationException("The task threw."))); @@ -533,7 +535,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) .Returns(Task.FromException>(new OperationCanceledException())); @@ -550,7 +552,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); using CancellationTokenSource cancellationTokenSource = new(); _mockTaskExecutor.When(executor => executor.ExecutePayloadAsync(Arg.Any(), Arg.Any())) .Do(_ => cancellationTokenSource.Cancel()); @@ -570,7 +572,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob); Assert.True(_runtimeRegistry.TryAcquireRunSlot(scheduledJobId)); // Act @@ -589,7 +591,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity addedJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Added, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(addedJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(addedJob, runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(addedJob, runningJob); _mockDomainEventPublisher.When(publisher => publisher.PublishAsync(Arg.Any(), Arg.Any())) .Do(_ => throw new OperationCanceledException()); @@ -659,7 +661,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -681,7 +683,7 @@ public class ScheduledJobSchedulerJobTests { // Arrange ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) .Returns(Error.Failure("ScheduledJobs.NotFound", "Failed to read the scheduled job")); // Act @@ -697,7 +699,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure("ScheduledJobExecutions.NotFound", "Failed to read the open execution")); @@ -736,7 +738,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(null)); @@ -755,7 +757,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); _mockScheduledJobRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -775,7 +777,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); _mockScheduledJobExecutionRepository.UpdateAsync(Arg.Any(), Arg.Any()) @@ -795,10 +797,10 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new InvalidOperationException("Save failed"))); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException>(new InvalidOperationException("Save failed"))); // Act ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); @@ -813,10 +815,10 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException(new OperationCanceledException())); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.FromException>(new OperationCanceledException())); // Act ScheduledJobStatus result = await InvokeAsync("ReconcileInterruptedRunAsync", scheduledJobId, CancellationToken.None); @@ -846,7 +848,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: false, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -868,7 +870,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(runningJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { runningJob }); // The first read reconciles the interrupted run while the job is still running; the reads made by the resumed cycle observe the reconciled active status. - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(runningJob, activeJob, activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(runningJob, activeJob, activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(_scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.OnceAtStartup)); ScheduledJobExecutionEntity openExecution = _scheduledJobExecutionEntityFixture.Create(scheduledJobId: runningJob.Id, isCycleRun: false, wasCycleActive: true, completedOnUtc: null); _mockScheduledJobExecutionRepository.GetOpenByScheduledJobIdAsync(Arg.Any(), Arg.Any()).Returns(openExecution); @@ -888,7 +890,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); _mockScheduledJobRepository.GetActiveOrRunningAsync(Arg.Any()).Returns(new[] { activeJob }); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); // Act await InvokeAsync("ResumeActiveCyclesAsync", CancellationToken.None); @@ -907,7 +909,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); RegisterDateTimeProvider(); IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); @@ -931,7 +933,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity dailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); ScheduledJobEntity runningDailyJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.DailyAtHourAndMinute, hour: 10, minute: 30); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(dailyJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(dailyJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(dailyJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningDailyJob); RegisterDateTimeProvider(); IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); @@ -955,7 +957,7 @@ public class ScheduledJobSchedulerJobTests ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobEntity runningJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Running, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); _mockScheduledJobRepository.GetByIdWithoutTrackingAsync(Arg.Any(), Arg.Any()).Returns(runningJob); RegisterDateTimeProvider(); _mockTaskExecutor.ExecutePayloadAsync(Arg.Any(), Arg.Any()) @@ -981,7 +983,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); RegisterDateTimeProvider(); using CancellationTokenSource cancellationTokenSource = new(); cancellationTokenSource.Cancel(); @@ -1000,7 +1002,7 @@ public class ScheduledJobSchedulerJobTests // Arrange ScheduledJobEntity activeJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 60); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(activeJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(activeJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(activeJob); RegisterDateTimeProvider(); IScheduledJobCycleTicker mockCycleTicker = Substitute.For(); mockCycleTicker.WaitForNextTickAsync(Arg.Any()) @@ -1038,7 +1040,7 @@ public class ScheduledJobSchedulerJobTests // An interval schedule whose interval is not positive cannot be converted to its domain object. ScheduledJobEntity invalidJob = _scheduledJobEntityFixture.Create(status: ScheduledJobStatus.Active, scheduleType: ScheduleType.WithIntervalInMinutes, intervalMinutes: 0); ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create(invalidJob.Id); - _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), Arg.Any()).Returns(invalidJob); + _mockScheduledJobRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()).Returns(invalidJob); // Act Schedule? result = await InvokeAsync("GetScheduleAsync", scheduledJobId, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs index 0cbb40d1..cf830d78 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/CleanScheduledJobExecutionHistoryTaskExecutorTests.cs @@ -37,6 +37,7 @@ public class CleanScheduledJobExecutionHistoryTaskExecutorTests { _mockDateTimeProvider = Substitute.For(); _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockScheduledJobExecutionRepository = Substitute.For(); _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); _mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs index ed5ca893..8e5ff46a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Scheduling/Execution/TaskExecutors/MediaLibraryScanTaskExecutorTests.cs @@ -44,7 +44,7 @@ public class MediaLibraryScanTaskExecutorTests _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) .Returns(Result.From>([])); _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockDomainEventPublisher = Substitute.For(); _sut = new MediaLibraryScanTaskExecutor(_mockDomainEventPublisher, Substitute.For>(), _mockUnitOfWork); } 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 fc7632b1..da6291a3 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 @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +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.Domain.Common.Primitives; @@ -42,7 +44,7 @@ public class RepairThemesTaskExecutorTests _mockUnitOfWork = Substitute.For(); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); ILogger logger = Substitute.For>(); _sut = new RepairThemesTaskExecutor(_mockThemeService, logger, _mockUnitOfWork); } @@ -53,14 +55,14 @@ public class RepairThemesTaskExecutorTests // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); _mockThemeService.GetBundledThemeArchivePaths().Returns([]); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); // Assert Assert.False(result.IsFailure); - await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockThemeRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -72,14 +74,14 @@ 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(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [], CurrentPage = 1, PerPage = 0, Count = 0, NumberOfPages = 1 })); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); // Assert Assert.False(result.IsFailure); - await _mockThemeRepository.Received(1).GetAllAsync(Arg.Any()); + await _mockThemeRepository.Received(1).GetAllAsync(cancellationToken: Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } @@ -88,8 +90,8 @@ public class RepairThemesTaskExecutorTests { // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Task.FromException>>(new InvalidOperationException("The database is unavailable."))); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Task.FromException>>(new InvalidOperationException("The database is unavailable."))); // Act Result result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None); @@ -104,8 +106,8 @@ public class RepairThemesTaskExecutorTests { // Arrange ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes); - _mockThemeRepository.GetAllAsync(Arg.Any()) - .Returns(Task.FromException>>(new OperationCanceledException())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) + .Returns(Task.FromException>>(new OperationCanceledException())); // Act async Task Act() diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs index af45a663..5c7e7635 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeSynchronizerTests.cs @@ -2,6 +2,8 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; +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.DataAccess.Entities.Themes; @@ -46,12 +48,12 @@ public class ThemeSynchronizerTests : IDisposable _mockUnitOfWork = Substitute.For(); _mockThemeRepository = Substitute.For(); _mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository); - _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockLogger = Substitute.For(); _mockThemeService.GetBundledThemeArchivePaths().Returns([]); _mockThemeService.HasThemePack(Arg.Any()).Returns(true); _mockThemeService.DefaultThemeId.Returns("lumina-default"); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(Result.From(Enumerable.Empty())); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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); @@ -63,7 +65,7 @@ public class ThemeSynchronizerTests : IDisposable public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn() { // Arrange - _mockThemeRepository.GetAllAsync(Arg.Any()) + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()) .Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes")); _mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]); @@ -97,7 +99,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(Arg.Any()).Returns(new[] { installedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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)); @@ -115,7 +117,7 @@ public class ThemeSynchronizerTests : IDisposable // Arrange ThemeManifestDto manifest = _themeManifestDtoFixture.Create(); ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { deletedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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)); @@ -133,7 +135,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(Arg.Any()).Returns(new[] { damagedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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. @@ -155,7 +157,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(Arg.Any()).Returns(new[] { damagedTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [damagedTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); string archivePath = CreateArchiveFile(); _mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]); _mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true); @@ -254,7 +256,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { healthyTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [healthyTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); // Act await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None); @@ -269,7 +271,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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); @@ -287,7 +289,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { lastBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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")); @@ -306,7 +308,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(Arg.Any()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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")); @@ -326,7 +328,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(Arg.Any()).Returns(new[] { brokenBundledTheme, healthyBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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")); @@ -346,7 +348,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenUserTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { Data = [brokenUserTheme], CurrentPage = 1, PerPage = 1, Count = 1, NumberOfPages = 1 })); _mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false); // Act @@ -361,7 +363,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenUserTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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")); @@ -380,7 +382,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(Arg.Any()).Returns(new[] { throwingBundledTheme, healthyBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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"))); @@ -401,7 +403,7 @@ public class ThemeSynchronizerTests : IDisposable { // Arrange ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false); - _mockThemeRepository.GetAllAsync(Arg.Any()).Returns(new[] { brokenBundledTheme }); + _mockThemeRepository.GetAllAsync(cancellationToken: Arg.Any()).Returns(Result.From(new PaginatedResultDto { 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.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs index 6fddda13..a665a0af 100644 --- a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs @@ -210,33 +210,27 @@ public class CalibreMapperTests MediaContributorDto author = result.Contributors[0]; Assert.Equal("Test Author", author.Name!.DisplayName); - Assert.Equal("Author", author.Role!.Name); - Assert.Equal(MediaContributorRoleCategory.Author, author.Role.Category); + Assert.Equal(MediaContributorRole.Author, author.Role); MediaContributorDto coAuthor = result.Contributors[1]; Assert.Equal("Co Author", coAuthor.Name!.DisplayName); - Assert.Equal("Author", coAuthor.Role!.Name); - Assert.Equal(MediaContributorRoleCategory.Author, coAuthor.Role.Category); + Assert.Equal(MediaContributorRole.Author, coAuthor.Role); MediaContributorDto translator = result.Contributors[2]; Assert.Equal("Test Translator", translator.Name!.DisplayName); - Assert.Equal("trl", translator.Role!.Name); - Assert.Equal(MediaContributorRoleCategory.Translator, translator.Role.Category); + Assert.Equal(MediaContributorRole.Translator, translator.Role); MediaContributorDto illustrator = result.Contributors[3]; Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName); - Assert.Equal("ill", illustrator.Role!.Name); - Assert.Equal(MediaContributorRoleCategory.Illustrator, illustrator.Role.Category); + Assert.Equal(MediaContributorRole.Illustrator, illustrator.Role); MediaContributorDto production = result.Contributors[4]; Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName); - Assert.Equal("bkp", production.Role!.Name); - Assert.Equal(MediaContributorRoleCategory.Publisher, production.Role.Category); + Assert.Equal(MediaContributorRole.Publisher, production.Role); MediaContributorDto misc = result.Contributors[5]; Assert.Equal("Misc Contributor", misc.Name!.DisplayName); - Assert.Equal("Contributor", misc.Role!.Name); - Assert.Equal(MediaContributorRoleCategory.Other, misc.Role.Category); + Assert.Equal(MediaContributorRole.Other, misc.Role); } [Fact] diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs index 5d27a75e..826398e1 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs @@ -48,50 +48,4 @@ public class PluginSettingDescriptorDtoTests Assert.Null(result.DefaultValue); Assert.Null(result.AllowedValues); } - - [Fact] - public void Equality_WhenTwoDescriptorsHaveTheSameValues_ShouldBeEqual() - { - // Arrange - IReadOnlyList allowedValues = ["A"]; - - // Act - PluginSettingDescriptorDto first = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: allowedValues); - PluginSettingDescriptorDto second = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: allowedValues); - bool result = first == second; - - // Assert - Assert.True(result); - Assert.Equal(first, second); - Assert.Equal(first.GetHashCode(), second.GetHashCode()); - } - - [Fact] - public void Equality_WhenDescriptorsHaveDifferentAllowedValueInstances_ShouldNotBeEqual() - { - // Arrange - PluginSettingDescriptorDto first = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: ["A"]); - PluginSettingDescriptorDto second = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: ["A"]); - - // Act - bool result = first == second; - - // Assert - Assert.False(result); - } - - [Fact] - public void Equality_WhenTwoDescriptorsHaveDifferentKeys_ShouldNotBeEqual() - { - // Arrange - PluginSettingDescriptorDto first = _pluginSettingDescriptorDtoFixture.Create(key: "KeyOne", label: "Label", type: PluginSettingType.Text); - PluginSettingDescriptorDto second = _pluginSettingDescriptorDtoFixture.Create(key: "KeyTwo", label: "Label", type: PluginSettingType.Text); - - // Act - bool result = first == second; - - // Assert - Assert.False(result); - Assert.NotEqual(first, second); - } } 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 6411a257..d6413507 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs @@ -30,7 +30,7 @@ public class IMetadataProviderGenericTests // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false); + BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Search Result", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false); TestBookMetadataProvider provider = new(expectedMetadata); IMetadataProvider baseProvider = provider; @@ -50,7 +50,7 @@ public class IMetadataProviderGenericTests // Arrange BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false); + BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Exact Result", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false); TestBookMetadataProvider provider = new(expectedMetadata); IMetadataProvider baseProvider = provider; @@ -68,7 +68,7 @@ public class IMetadataProviderGenericTests { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); - TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false)); + TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Search Result", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false)); IMetadataProvider baseProvider = provider; // Act @@ -87,7 +87,7 @@ public class IMetadataProviderGenericTests { // Arrange MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); - TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false)); + TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeReleaseInfo: false, includeGenres: false, includeTags: false, includeLanguage: false, includeFormat: false, includeVolumeNumber: false)); IMetadataProvider baseProvider = provider; // Act 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 4a0bb823..5218aefa 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs @@ -170,20 +170,18 @@ public class OpenLibraryMapperTests oclc: ["123456789"]); // Act - AddBookRequest result = OpenLibraryMapper.MapSearchCandidate(lookup, document); + BookMetadataDto result = OpenLibraryMapper.MapSearchCandidate(lookup, document); // Assert - Assert.Equal(lookup.LibraryId, result.LibraryId); - Assert.Equal(lookup.Path, result.Path); - Assert.Equal("Search Title", result.Metadata!.Title); - Assert.Equal(2003, result.Metadata.ReleaseInfo!.OriginalReleaseYear); - Assert.Equal("Search Publisher", result.Metadata.Publisher); - Assert.Equal(250, result.Metadata.PageCount); - Assert.Contains(result.Metadata.Genres!, genre => genre.Name == "Science fiction"); - Assert.DoesNotContain(result.Metadata.Genres!, genre => genre.Name == "Space"); - Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Science fiction"); - Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Space"); - Assert.Null(result.Metadata.ReleaseInfo.ReleaseCountry); + Assert.Equal("Search Title", result.Title); + Assert.Equal(2003, result.ReleaseInfo!.OriginalReleaseYear); + Assert.Equal("Search Publisher", result.Publisher); + Assert.Equal(250, result.PageCount); + Assert.Contains(result.Genres!, genre => genre.Name == "Science fiction"); + Assert.DoesNotContain(result.Genres!, genre => genre.Name == "Space"); + Assert.Contains(result.Tags!, tag => tag.Name == "Science fiction"); + Assert.Contains(result.Tags!, tag => tag.Name == "Space"); + Assert.Null(result.ReleaseInfo.ReleaseCountry); BookRatingDto rating = Assert.Single(result.Ratings!); Assert.Equal(4.1m, rating.Value); Assert.Equal(5m, rating.MaxValue); @@ -192,8 +190,8 @@ public class OpenLibraryMapperTests Assert.Equal("79042755", result.LCCN); Assert.Equal("123456789", result.OCLCNumber); Assert.Equal("OL12345W", result.OpenLibraryId); - Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); - Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role!.Name == "Author"); + Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role == MediaContributorRole.Author); } [Fact] @@ -235,33 +233,31 @@ public class OpenLibraryMapperTests OpenLibraryRatingsResponse ratings = _ratingsResponseFixture.Create(_ratingSummaryResponseFixture.Create(average: 4.2m, count: 100)); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings); // Assert - Assert.Equal(lookup.LibraryId, result.LibraryId); - Assert.Equal(lookup.Path, result.Path); - Assert.Equal("Edition Title", result.Metadata!.Title); - Assert.Equal("Original Title", result.Metadata.OriginalTitle); - Assert.Equal("A work description", result.Metadata.Description); - Assert.Equal(new DateOnly(1987, 6, 1), result.Metadata.ReleaseInfo!.OriginalReleaseDate); - Assert.Equal(1987, result.Metadata.ReleaseInfo.OriginalReleaseYear); - Assert.Equal(new DateOnly(2010, 5, 1), result.Metadata.ReleaseInfo.ReReleaseDate); - Assert.Equal(2010, result.Metadata.ReleaseInfo.ReReleaseYear); - Assert.Null(result.Metadata.ReleaseInfo.ReleaseCountry); - Assert.Equal("First Edition", result.Metadata.ReleaseInfo.ReleaseVersion); - GenreDto genre = Assert.Single(result.Metadata.Genres!); + Assert.Equal("Edition Title", result.Title); + Assert.Equal("Original Title", result.OriginalTitle); + Assert.Equal("A work description", result.Description); + Assert.Equal(new DateOnly(1987, 6, 1), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1987, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(2010, 5, 1), result.ReleaseInfo.ReReleaseDate); + Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Equal("First Edition", result.ReleaseInfo.ReleaseVersion); + GenreDto genre = Assert.Single(result.Genres!); Assert.Equal("Fantasy", genre.Name); - Assert.Equal(3, result.Metadata.Tags!.Count); - Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Science fiction"); - Assert.Contains(result.Metadata.Tags, tag => tag.Name == "History"); - Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Space"); - Assert.Equal("en", result.Metadata.Language!.LanguageCode); - Assert.False(string.IsNullOrWhiteSpace(result.Metadata.Language.LanguageName)); - Assert.Equal("fre", result.Metadata.OriginalLanguage!.LanguageCode); - Assert.Equal("fre", result.Metadata.OriginalLanguage.LanguageName); - Assert.Null(result.Metadata.OriginalLanguage.NativeName); - Assert.Equal("Publisher Co", result.Metadata.Publisher); - Assert.Equal(320, result.Metadata.PageCount); + Assert.Equal(3, result.Tags!.Count); + Assert.Contains(result.Tags, tag => tag.Name == "Science fiction"); + Assert.Contains(result.Tags, tag => tag.Name == "History"); + Assert.Contains(result.Tags, tag => tag.Name == "Space"); + Assert.Equal("en", result.Language!.LanguageCode); + Assert.False(string.IsNullOrWhiteSpace(result.Language.LanguageName)); + Assert.Equal("fre", result.OriginalLanguage!.LanguageCode); + Assert.Equal("fre", result.OriginalLanguage.LanguageName); + Assert.Null(result.OriginalLanguage.NativeName); + Assert.Equal("Publisher Co", result.Publisher); + Assert.Equal(320, result.PageCount); Assert.Equal(BookFormat.Hardcover, result.Format); Assert.Equal("First Edition", result.Edition); Assert.Equal(3, result.VolumeNumber); @@ -275,10 +271,10 @@ public class OpenLibraryMapperTests Assert.Equal("gid", result.GoogleBooksId); Assert.Equal("bnid", result.BarnesAndNobleId); Assert.Equal("apid", result.AppleBooksId); - Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); - Assert.Contains(result.ISBNs!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10); - Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role!.Name == "Author"); - Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == MediaContributorRoleCategory.Illustrator); + Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); + Assert.Contains(result.Isbns!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role == MediaContributorRole.Author); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role == MediaContributorRole.Illustrator); BookRatingDto mappedRating = Assert.Single(result.Ratings!); Assert.Equal(4.2m, mappedRating.Value); Assert.Equal(5m, mappedRating.MaxValue); @@ -294,13 +290,13 @@ public class OpenLibraryMapperTests OpenLibraryWorkResponse work = _workResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); // Assert - Assert.Equal(2, result.Metadata!.Genres!.Count); - Assert.Contains(result.Metadata.Genres, genre => genre.Name == "Science fiction"); - Assert.Contains(result.Metadata.Genres, genre => genre.Name == "History"); - Assert.DoesNotContain(result.Metadata.Genres, genre => genre.Name == "Space"); + Assert.Equal(2, result.Genres!.Count); + Assert.Contains(result.Genres, genre => genre.Name == "Science fiction"); + Assert.Contains(result.Genres, genre => genre.Name == "History"); + Assert.DoesNotContain(result.Genres, genre => genre.Name == "Space"); } [Fact] @@ -311,11 +307,11 @@ public class OpenLibraryMapperTests OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(firstPublishYear: 2001); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); // Assert - Assert.Equal(2001, result.Metadata!.ReleaseInfo!.OriginalReleaseYear); - Assert.Null(result.Metadata.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(2001, result.ReleaseInfo!.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); } [Fact] @@ -326,13 +322,13 @@ public class OpenLibraryMapperTests OpenLibraryEditionResponse edition = _editionResponseFixture.Create(languages: [_keyReferenceResponseFixture.Create(key: "/languages/xxq")]); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); // Assert - Assert.NotNull(result.Metadata!.Language); - Assert.Equal("xxq", result.Metadata.Language!.LanguageCode); - Assert.Equal("xxq", result.Metadata.Language.LanguageName); - Assert.Null(result.Metadata.Language.NativeName); + Assert.NotNull(result.Language); + Assert.Equal("xxq", result.Language!.LanguageCode); + Assert.Equal("xxq", result.Language.LanguageName); + Assert.Null(result.Language.NativeName); } [Fact] @@ -343,10 +339,10 @@ public class OpenLibraryMapperTests OpenLibraryWorkResponse work = _workResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); // Assert - Assert.Equal("A plain description", result.Metadata!.Description); + Assert.Equal("A plain description", result.Description); } [Fact] @@ -356,17 +352,15 @@ public class OpenLibraryMapperTests BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7"); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null); // Assert - Assert.Equal(lookup.LibraryId, result.LibraryId); - Assert.Equal(lookup.Path, result.Path); - Assert.NotNull(result.Metadata); - Assert.Null(result.Metadata!.Title); + Assert.NotNull(result); + Assert.Null(result.Title); Assert.Null(result.Format); Assert.Null(result.Edition); Assert.Null(result.OpenLibraryId); - Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157"); + Assert.Contains(result.Isbns!, isbn => isbn.Value == "9780306406157"); Assert.Empty(result.Ratings!); Assert.Empty(result.Contributors!); } @@ -379,7 +373,7 @@ public class OpenLibraryMapperTests OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); // Assert BookRatingDto rating = Assert.Single(result.Ratings!); @@ -395,7 +389,7 @@ public class OpenLibraryMapperTests OpenLibraryEditionResponse edition = _editionResponseFixture.Create(series: ["Book 2 of the trilogy"]); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); // Assert Assert.Equal(2, result.VolumeNumber); @@ -420,7 +414,7 @@ public class OpenLibraryMapperTests oclc: ["888888"]); // Act - AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback); + BookMetadataDto result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback); // Assert Assert.Equal("B000002", result.ASIN); diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs index 8d43ba9e..1c4994f0 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs @@ -339,12 +339,12 @@ public class OpenLibraryBookMetadataProviderTests OpenLibraryBookMetadataProvider sut = CreateProvider(handler); // Act - AddBookRequest? result = await sut.GetBookAsync(lookup); + BookMetadataDto? result = await sut.GetBookAsync(lookup); // Assert Assert.NotNull(result); - Assert.Equal("Edition Title", result!.Metadata!.Title); - Assert.Equal("A work description", result.Metadata.Description); + Assert.Equal("Edition Title", result.Title); + Assert.Equal("A work description", result.Description); Assert.Equal("OL100M", result.OpenLibraryId); Assert.Equal(BookFormat.Hardcover, result.Format); Assert.Equal(3, result.VolumeNumber); @@ -370,11 +370,11 @@ public class OpenLibraryBookMetadataProviderTests OpenLibraryBookMetadataProvider sut = CreateProvider(handler); // Act - AddBookRequest? result = await sut.GetBookAsync(lookup); + BookMetadataDto? result = await sut.GetBookAsync(lookup); // Assert Assert.NotNull(result); - Assert.Equal("Work Title", result!.Metadata!.Title); + Assert.Equal("Work Title", result.Title); Assert.Equal("OL200W", result.OpenLibraryId); } @@ -389,11 +389,11 @@ public class OpenLibraryBookMetadataProviderTests OpenLibraryBookMetadataProvider sut = CreateProvider(handler); // Act - AddBookRequest? result = await sut.GetBookAsync(lookup); + BookMetadataDto? result = await sut.GetBookAsync(lookup); // Assert Assert.NotNull(result); - Assert.Equal("Fallback Edition", result!.Metadata!.Title); + Assert.Equal("Fallback Edition", result.Title); Assert.Equal("OL600M", result.OpenLibraryId); Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/books/OL600M.json"); } @@ -408,7 +408,7 @@ public class OpenLibraryBookMetadataProviderTests OpenLibraryBookMetadataProvider sut = CreateProvider(handler); // Act - AddBookRequest? result = await sut.GetBookAsync(lookup); + BookMetadataDto? result = await sut.GetBookAsync(lookup); // Assert Assert.Null(result); 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 8c6f3287..e80810c0 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 @@ -60,7 +60,7 @@ public class GetPermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index ba93fd07..25b6fd89 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -62,7 +62,7 @@ public class AddRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange AddRoleRequest request = _addRoleRequestFixture.Create(roleName: "Admin", permissions: [Guid.NewGuid()]); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index 6ca63441..a6182ebe 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -52,7 +52,7 @@ public class DeleteRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange DeleteRoleRequest request = _deleteRoleRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs index dc159cc9..507e06b9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -64,7 +64,7 @@ public class GetRolePermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index ef0ae8d6..87d446fd 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -58,7 +58,7 @@ public class GetRolesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs index dd210b29..5dd5d089 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -65,7 +65,7 @@ public class UpdateRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange UpdateRoleRequest request = _updateRoleRequestFixture.Create(roleName: "UpdatedAdmin"); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs index 2148d262..9d0c009e 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Common/BaseEndpointTests.cs @@ -107,7 +107,7 @@ public class BaseEndpointTests // Assert ProblemHttpResult problemResult = Assert.IsType(result); - Assert.Equal(422, problemResult.StatusCode); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.ProblemDetails.Status); Assert.Equal("General.Validation", problemResult.ProblemDetails.Title); Assert.Equal("OneOrMoreValidationErrorsOccurred", problemResult.ProblemDetails.Detail); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs index 01355311..f6a354e6 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectoriesEndpointTests.cs @@ -60,7 +60,7 @@ public class GetDirectoriesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); @@ -86,7 +86,7 @@ public class GetDirectoriesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); @@ -112,7 +112,7 @@ public class GetDirectoriesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDirectoriesQueryToSender() { // Arrange GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(); @@ -125,7 +125,7 @@ public class GetDirectoriesEndpointTests // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(q => q.Path == request.Path && q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements), Arg.Is(cancellationToken)); } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 4a0cbc97..aabbba4b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -56,7 +56,7 @@ public class GetDrivesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -81,7 +81,7 @@ public class GetDrivesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetDrivesQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index b1836ba6..39525c6b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -73,7 +73,7 @@ public class GetTypeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetFileSystemQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 04e95ae8..24250a59 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -60,7 +60,7 @@ public class GetFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetFilesRequest request = _getFilesRequestFixture.Create(); @@ -86,7 +86,7 @@ public class GetFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetFilesRequest request = _getFilesRequestFixture.Create(); @@ -126,7 +126,7 @@ public class GetFilesEndpointTests // Assert await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path && - q.IncludeHiddenElements == request.IncludeHiddenElements), + q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements), Arg.Is(cancellationToken)); } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index 4f6d6440..7ad68f3f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -60,7 +60,7 @@ public class GetTreeFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); @@ -86,7 +86,7 @@ public class GetTreeFilesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetTreeFilesRequest request = _getTreeFilesRequestFixture.Create(); @@ -126,7 +126,7 @@ public class GetTreeFilesEndpointTests // Assert await _mockHandler.Received(1).HandleAsync(Arg.Is(q => q.Path == request.Path && - q.IncludeHiddenElements == request.IncludeHiddenElements), + q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements), Arg.Is(cancellationToken)); } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index 7f1ce540..d5fae9cc 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -43,7 +43,7 @@ public class CheckPathExistsEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResultWithPathExistsResponse() { // Arrange - CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", shouldIncludeHiddenElements: true); CancellationToken cancellationToken = CancellationToken.None; PathExistsResponse expectedResponse = _pathExistsResponseFixture.Create(exists: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -58,10 +58,10 @@ public class CheckPathExistsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckPathExistsQueryToSender() { // Arrange - CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", shouldIncludeHiddenElements: true); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(_pathExistsResponseFixture.Create(exists: true)); @@ -71,7 +71,7 @@ public class CheckPathExistsEndpointTests // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(q => q.Path == request.Path && q.IncludeHiddenElements == request.IncludeHiddenElements), + Arg.Is(q => q.Path == request.Path && q.ShouldIncludeHiddenElements == request.ShouldIncludeHiddenElements), Arg.Is(cancellationToken)); } @@ -79,7 +79,7 @@ public class CheckPathExistsEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); + CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", shouldIncludeHiddenElements: true); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index e46be9e1..80380e2a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -57,7 +57,7 @@ public class CombinePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser"); @@ -83,7 +83,7 @@ public class CombinePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange CombinePathRequest request = _combinePathRequestFixture.Create("InvalidPath", "TestUser"); @@ -109,7 +109,7 @@ public class CombinePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendCombinePathCommandToSender() { // Arrange CombinePathRequest request = _combinePathRequestFixture.Create("C:\\Users", "TestUser"); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index 12f46f8f..f47854cb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -60,7 +60,7 @@ public class GetPathParentEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); @@ -86,7 +86,7 @@ public class GetPathParentEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetPathParentRequest request = _getPathParentRequestFixture.Create(@"InvalidPath"); @@ -112,7 +112,7 @@ public class GetPathParentEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathParentQueryToSender() { // Arrange GetPathParentRequest request = _getPathParentRequestFixture.Create(@"C:\Users\TestUser"); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index 114649d4..48ada628 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -58,7 +58,7 @@ public class GetPathRootEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); @@ -84,7 +84,7 @@ public class GetPathRootEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetPathRootRequest request = _getPathRootRequestFixture.Create(@"InvalidPath"); @@ -110,7 +110,7 @@ public class GetPathRootEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathRootQueryToSender() { // Arrange GetPathRootRequest request = _getPathRootRequestFixture.Create(@"C:\Users\TestUser"); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs index a6d471ce..e48b7772 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -53,7 +53,7 @@ public class GetPathSeparatorEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPathSeparatorQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index 26e8ec27..17acd674 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -59,7 +59,7 @@ public class SplitPathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange SplitPathRequest request = _splitPathRequestFixture.Create(@"InvalidPath"); @@ -86,7 +86,7 @@ public class SplitPathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendSplitPathCommandToSender() { // Arrange SplitPathRequest request = _splitPathRequestFixture.Create(@"C:\Users\TestUser\Documents"); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 14e9327b..937906f3 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -58,7 +58,7 @@ public class ValidatePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendValidatePathQueryToSender() { // Arrange ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); @@ -76,7 +76,7 @@ public class ValidatePathEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index 689fb0f5..ae8a0b8d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -60,7 +60,7 @@ public class GetThumbnailEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80); @@ -86,7 +86,7 @@ public class GetThumbnailEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetThumbnailRequest request = _getThumbnailRequestFixture.Create("/path/to/nonexistent/file.jpg", 80); 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 new file mode 100644 index 00000000..1d63089b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointTests.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.AddAlbum; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.AddAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddAlbumEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddAlbumEndpoint _sut; + private readonly AddAlbumRequestFixture _addAlbumRequestFixture = new(); + private readonly AlbumResponseFixture _albumResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddAlbumEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLocationAndAlbumResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + AlbumResponse expectedResponse = _albumResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, createdResult.Value); + Assert.NotNull(createdResult.Location); + Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{expectedResponse.Id}", createdResult.Location); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.AlbumTitleCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumTitleCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddAlbumCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.Metadata == request.Metadata && + command.MediaFormat == request.MediaFormat && + command.Barcode == request.Barcode && + command.CatalogNumber == request.CatalogNumber && + command.MusicBrainzReleaseId == request.MusicBrainzReleaseId && + command.MusicBrainzReleaseGroupId == request.MusicBrainzReleaseGroupId && + command.MusicBrainzReleaseArtistId == request.MusicBrainzReleaseArtistId && + command.Contributors == request.Contributors && + command.Ratings == request.Ratings && + command.Tracks != null && + command.Tracks.Count == request.Tracks!.Count && + command.Tracks[0].LibraryId == libraryId.ToString() && + command.Tracks[0].ArtistId == artistId.ToString() && + command.Tracks[0].AlbumId == null && + command.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + AddAlbumRequest request = _addAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + AddAlbumRequest request = _addAlbumRequestFixture.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(_albumResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // 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/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs new file mode 100644 index 00000000..97ac046b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointTests.cs @@ -0,0 +1,240 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.DeleteAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteAlbumEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteAlbumEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteAlbumEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.AlbumNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("AlbumNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.AlbumIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteAlbumCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.AlbumId == albumId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid" && + command.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null && + command.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Populates the route values read by the endpoint. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs new file mode 100644 index 00000000..39ef927a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointTests.cs @@ -0,0 +1,259 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetAlbumEndpoint _sut; + private readonly AlbumResponseFixture _albumResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAlbumEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + AlbumResponse expectedResponse = _albumResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.AlbumNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("AlbumNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.AlbumIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetAlbumQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.AlbumId == albumId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid" && + query.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null && + query.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + 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(_albumResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs new file mode 100644 index 00000000..f79a44d3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointTests.cs @@ -0,0 +1,260 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracks; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetAlbumTracksEndpoint _sut; + private readonly TrackResponseFixture _trackResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _trackResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.AlbumNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("AlbumNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.AlbumIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetAlbumTracksQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_trackResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.AlbumId == albumId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_trackResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid" && + query.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_trackResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null && + query.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + 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((IReadOnlyList)_trackResponseFixture.CreateMany(1)); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs new file mode 100644 index 00000000..e6437a3b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointTests.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracksLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.GetAlbumTracksLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAlbumTracksLiteEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetAlbumTracksLiteEndpoint _sut; + private readonly GetAlbumTracksLiteRequestFixture _getAlbumTracksLiteRequestFixture = new(); + private readonly TrackLiteResponseFixture _trackLiteResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAlbumTracksLiteEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedTrackLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(trackCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _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.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.AlbumIdCannotBeEmpty; + _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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetAlbumTracksLiteQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(trackCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.AlbumId == albumId.ToString() && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(trackCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.AlbumId == albumId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(trackCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid" && + query.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(trackCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null && + query.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetAlbumTracksLiteRequest request = _getAlbumTracksLiteRequestFixture.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(CreatePaginatedResponse(trackCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of tracks. + /// + /// The number of track responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int trackCount) + { + List tracks = []; + for (int index = 0; index < trackCount; index++) + tracks.Add(_trackLiteResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: tracks, currentPage: 1, perPage: 10, count: trackCount, numberOfPages: trackCount > 0 ? 1 : 0); + } +} 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 new file mode 100644 index 00000000..a065ac95 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointTests.cs @@ -0,0 +1,279 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.UpdateAlbum; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.UpdateAlbum; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAlbumEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateAlbumEndpoint _sut; + private readonly UpdateAlbumRequestFixture _updateAlbumRequestFixture = new(); + private readonly AlbumResponseFixture _albumResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateAlbumEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + AlbumResponse expectedResponse = _albumResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.AlbumNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("AlbumNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.AlbumIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "AlbumIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateAlbumCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.AlbumId == albumId.ToString() && + command.Metadata == request.Metadata && + command.MediaFormat == request.MediaFormat && + command.Barcode == request.Barcode && + command.CatalogNumber == request.CatalogNumber && + command.MusicBrainzReleaseId == request.MusicBrainzReleaseId && + command.MusicBrainzReleaseGroupId == request.MusicBrainzReleaseGroupId && + command.MusicBrainzReleaseArtistId == request.MusicBrainzReleaseArtistId && + command.Contributors == request.Contributors && + command.Ratings == request.Ratings), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid" && + command.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + UpdateAlbumRequest request = _updateAlbumRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_albumResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null && + command.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + UpdateAlbumRequest request = _updateAlbumRequestFixture.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(_albumResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // 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/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs new file mode 100644 index 00000000..c907b11c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.AddArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.AddArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddArtistEndpoint _sut; + private readonly AddArtistRequestFixture _addArtistRequestFixture = new(); + private readonly ArtistResponseFixture _artistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLocationAndArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ArtistResponse expectedResponse = _artistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, createdResult.Value); + Assert.NotNull(createdResult.Location); + Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{expectedResponse.Id}", createdResult.Location); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _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.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _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.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddArtistCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.Name == request.Name && + command.Website == request.Website && + command.MusicBrainzArtistId == request.MusicBrainzArtistId && + command.Contributors == request.Contributors && + command.Albums != null && + command.Albums.Count == request.Albums!.Count && + command.Albums[0].LibraryId == libraryId.ToString() && + command.Albums[0].ArtistId == null && + command.Albums[0].Metadata == request.Albums[0].Metadata && + command.Albums[0].Tracks != null && + command.Albums[0].Tracks!.Count == request.Albums[0].Tracks!.Count), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithRawRouteValue() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullLibraryId() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddArtistRequest request = _addArtistRequestFixture.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(_artistResponseFixture.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/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs new file mode 100644 index 00000000..71a220f4 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointTests.cs @@ -0,0 +1,232 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.DeleteArtist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.DeleteArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteArtistEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteArtistCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Populates the route values read by the endpoint. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs new file mode 100644 index 00000000..8b3dc592 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointTests.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetArtistEndpoint _sut; + private readonly ArtistResponseFixture _artistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + ArtistResponse expectedResponse = _artistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + 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(_artistResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs new file mode 100644 index 00000000..58f7f801 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointTests.cs @@ -0,0 +1,243 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbums; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistAlbumsEndpoint _sut; + private readonly AlbumResponseFixture _albumResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAlbumResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _albumResponseFixture.CreateMany(2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.ArtistIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistAlbumsQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From((IReadOnlyList)_albumResponseFixture.CreateMany(1))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + 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((IReadOnlyList)_albumResponseFixture.CreateMany(1)); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs new file mode 100644 index 00000000..0405a1e0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointTests.cs @@ -0,0 +1,258 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbumsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistAlbumsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistAlbumsLiteEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistAlbumsLiteEndpoint _sut; + private readonly GetArtistAlbumsLiteRequestFixture _getArtistAlbumsLiteRequestFixture = new(); + private readonly AlbumLiteResponseFixture _albumLiteResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistAlbumsLiteEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedAlbumLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(albumCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _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.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistIdCannotBeEmpty; + _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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistAlbumsLiteQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(albumCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetArtistAlbumsLiteRequest request = _getArtistAlbumsLiteRequestFixture.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(CreatePaginatedResponse(albumCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of albums. + /// + /// The number of album responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int albumCount) + { + List albums = []; + for (int index = 0; index < albumCount; index++) + albums.Add(_albumLiteResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: albums, currentPage: 1, perPage: 10, count: albumCount, numberOfPages: albumCount > 0 ? 1 : 0); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs new file mode 100644 index 00000000..791de963 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtists; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistsEndpoint _sut; + private readonly GetArtistsRequestFixture _getArtistsRequestFixture = new(); + private readonly ArtistResponseFixture _artistResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedArtistResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(artistCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _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.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Library.LibraryIdCannotBeEmpty; + _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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistsQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsRequest request = _getArtistsRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetArtistsRequest request = _getArtistsRequestFixture.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(CreatePaginatedResponse(artistCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of artists. + /// + /// The number of artist responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int artistCount) + { + List artists = []; + for (int index = 0; index < artistCount; index++) + artists.Add(_artistResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: artists, currentPage: 1, perPage: 10, count: artistCount, numberOfPages: artistCount > 0 ? 1 : 0); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs new file mode 100644 index 00000000..538d1b45 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistsLite; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.GetArtistsLite; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetArtistsLiteEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetArtistsLiteEndpoint _sut; + private readonly GetArtistsLiteRequestFixture _getArtistsLiteRequestFixture = new(); + private readonly ArtistLiteResponseFixture _artistLiteResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetArtistsLiteEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedArtistLiteResponses() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = CreatePaginatedResponse(artistCount: 2); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _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.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Library.LibraryIdCannotBeEmpty; + _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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetArtistsLiteQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPaginationIsMissing_ShouldSendQueryWithNullPaginationData() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(includeCurrentPage: false, includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(artistCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetArtistsLiteRequest request = _getArtistsLiteRequestFixture.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(CreatePaginatedResponse(artistCount: 0)); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Creates a with the specified number of artists. + /// + /// The number of artist responses to include in the data collection. + /// A configured paginated response instance. + private PaginatedResponse CreatePaginatedResponse(int artistCount) + { + List artists = []; + for (int index = 0; index < artistCount; index++) + artists.Add(_artistLiteResponseFixture.Create()); + + return _paginatedResponseFixture.Create(data: artists, currentPage: 1, perPage: 10, count: artistCount, numberOfPages: artistCount > 0 ? 1 : 0); + } +} 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 new file mode 100644 index 00000000..dd3599f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointTests.cs @@ -0,0 +1,263 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Commands.UpdateArtist; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Artists.UpdateArtist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateArtistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateArtistEndpoint _sut; + private readonly UpdateArtistRequestFixture _updateArtistRequestFixture = new(); + private readonly ArtistResponseFixture _artistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateArtistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtistResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ArtistResponse expectedResponse = _artistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Errors.Music.ArtistNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.ArtistNameCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ArtistNameCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateArtistCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.Name == request.Name && + command.Website == request.Website && + command.MusicBrainzArtistId == request.MusicBrainzArtistId && + command.Contributors == request.Contributors && + command.Albums != null && + command.Albums.Count == request.Albums!.Count && + command.Albums[0].LibraryId == libraryId.ToString() && + command.Albums[0].ArtistId == artistId.ToString() && + command.Albums[0].AlbumId == request.Albums[0].AlbumId && + command.Albums[0].Metadata == request.Albums[0].Metadata), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + UpdateArtistRequest request = _updateArtistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_artistResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + UpdateArtistRequest request = _updateArtistRequestFixture.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(_artistResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + + // 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/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs new file mode 100644 index 00000000..b94aff9c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.AddTrack; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.AddTrack; +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.AudioLibrary.MusicLibrary.Tracks.AddTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddTrackEndpointTests +{ + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly AddTrackEndpoint _sut; + private readonly AddTrackRequestFixture _addTrackRequestFixture = new(); + private readonly TrackResponseFixture _trackResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddTrackEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLocationAndTrackResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddTrackRequest request = _addTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + TrackResponse expectedResponse = _trackResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, createdResult.Value); + Assert.NotNull(createdResult.Location); + Assert.EndsWith($"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{expectedResponse.Id}", createdResult.Location); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + AddTrackRequest request = _addTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Music.ArtistNotFound", "ArtistNotFound"); + _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.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("Music.ArtistNotFound", problemDetailsBody.Title); + Assert.Equal("ArtistNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddTrackRequest request = _addTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddTrackCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddTrackRequest request = _addTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.AlbumId == albumId.ToString() && + command.Path == request.Path && + command.Metadata == request.Metadata && + command.TrackNumber == request.TrackNumber && + command.DiscNumber == request.DiscNumber && + command.Script == request.Script && + command.Key == request.Key && + command.Bpm == request.Bpm && + 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 && + command.Ratings == request.Ratings), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + AddTrackRequest request = _addTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid" && + command.AlbumId == "not-an-album-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullRouteValues() + { + // Arrange + AddTrackRequest request = _addTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null && + command.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddTrackRequest request = _addTrackRequestFixture.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(_trackResponseFixture.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/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs new file mode 100644 index 00000000..f92595e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointTests.cs @@ -0,0 +1,247 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.DeleteTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteTrackEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteTrackEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteTrackEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = DomainErrors.Music.TrackNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("General.NotFound", problemDetailsBody.Title); + Assert.Equal("TrackNotFound", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = DomainErrors.Music.TrackIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + ConfigureRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "TrackIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteTrackCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.AlbumId == albumId.ToString() && + command.TrackId == trackId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + _sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid" && + command.AlbumId == "not-an-album-guid" && + command.TrackId == "not-a-track-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + _sut.HttpContext.Request.RouteValues.Remove("trackId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null && + command.AlbumId == null && + command.TrackId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + ConfigureRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Populates the route values read by the endpoint. + /// + private void ConfigureRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointTests.cs new file mode 100644 index 00000000..bff47cee --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointTests.cs @@ -0,0 +1,241 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrack; +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.AudioLibrary.MusicLibrary.Tracks.GetTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetTrackEndpoint _sut; + private readonly TrackResponseFixture _trackResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetTrackEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + TrackResponse expectedResponse = _trackResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Track.NotFound", "TrackNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("Track.NotFound", problemDetailsBody.Title); + Assert.Equal("TrackNotFound", problemDetailsBody.Detail); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.TrackIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "TrackIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetTrackQueryToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.ArtistId == artistId.ToString() && + query.AlbumId == albumId.ToString() && + query.TrackId == trackId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + _sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.ArtistId == "not-an-artist-guid" && + query.AlbumId == "not-an-album-guid" && + query.TrackId == "not-a-track-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + _sut.HttpContext.Request.RouteValues.Remove("trackId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null && + query.AlbumId == null && + query.TrackId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + 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(_trackResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs new file mode 100644 index 00000000..f4c557f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointTests.cs @@ -0,0 +1,266 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.UpdateTrack; +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.AudioLibrary.MusicLibrary.Tracks.UpdateTrack; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateTrackEndpointTests +{ + private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly UpdateTrackEndpoint _sut; + private readonly UpdateTrackRequestFixture _updateTrackRequestFixture = new(); + private readonly TrackResponseFixture _trackResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateTrackEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponse() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + TrackResponse expectedResponse = _trackResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Track.NotFound", "TrackNotFound"); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status); + Assert.Equal("Track.NotFound", problemDetailsBody.Title); + Assert.Equal("TrackNotFound", problemDetailsBody.Detail); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Music.TrackPathCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "TrackPathCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateTrackCommandToSender() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId.ToString() && + command.ArtistId == artistId.ToString() && + command.AlbumId == albumId.ToString() && + command.TrackId == trackId.ToString() && + command.Path == request.Path && + command.Metadata == request.Metadata && + command.TrackNumber == request.TrackNumber && + command.DiscNumber == request.DiscNumber && + command.Script == request.Script && + command.Key == request.Key && + command.Bpm == request.Bpm && + 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 && + command.Ratings == request.Ratings), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() + { + // Arrange + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["artistId"] = "not-an-artist-guid"; + _sut.HttpContext.Request.RouteValues["albumId"] = "not-an-album-guid"; + _sut.HttpContext.Request.RouteValues["trackId"] = "not-a-track-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == "not-a-library-guid" && + command.ArtistId == "not-an-artist-guid" && + command.AlbumId == "not-an-album-guid" && + command.TrackId == "not-a-track-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + UpdateTrackRequest request = _updateTrackRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("artistId"); + _sut.HttpContext.Request.RouteValues.Remove("albumId"); + _sut.HttpContext.Request.RouteValues.Remove("trackId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == null && + command.ArtistId == null && + command.AlbumId == null && + command.TrackId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + UpdateTrackRequest request = _updateTrackRequestFixture.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(_trackResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = artistId.ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = albumId.ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = trackId.ToString(); + + // Act + 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/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index f4bcac14..2cf25f02 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -57,7 +57,7 @@ public class AddLibraryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnProblemResult() { // Arrange AddLibraryRequest request = _addLibraryRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs index 3d855f74..9959f94e 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -48,7 +48,7 @@ public class CancelLibrariesScanEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -73,7 +73,7 @@ public class CancelLibrariesScanEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCancelLibrariesScanCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendCancelLibrariesScanCommandToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs index e6250145..8b314617 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -52,7 +52,7 @@ public class CancelLibraryScanEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange CancelLibraryScanRequest request = _cancelLibraryScanRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index 611d3de9..5df1f873 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -53,7 +53,7 @@ public class DeleteLibraryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs index 37ce926d..0337e3d5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -55,7 +55,7 @@ public class GetEnabledLibrariesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -80,7 +80,7 @@ public class GetEnabledLibrariesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetEnabledLibrariesQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetEnabledLibrariesQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs index d7bd168b..75425db0 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -55,7 +55,7 @@ public class GetLibrariesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -80,7 +80,7 @@ public class GetLibrariesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibrariesQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibrariesQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs index 4c4f6823..512589aa 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs @@ -59,7 +59,7 @@ public class GetLibraryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetLibraryRequest request = _getLibraryRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs index d5b39d5c..e5d68a49 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs @@ -58,7 +58,7 @@ public class GetLibraryScanProgressEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetLibraryScanProgressRequest request = _getLibraryScanProgressRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs index e3bcca5b..0ad08552 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -60,7 +60,7 @@ public class GetRunningLibraryScansEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -85,7 +85,7 @@ public class GetRunningLibraryScansEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetRunningLibraryScansQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetRunningLibraryScansQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs index b86bf9ab..b6c7b282 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -59,7 +59,7 @@ public class ScanLibrariesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -84,7 +84,7 @@ public class ScanLibrariesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendScanLibrariesCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendScanLibrariesCommandToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs index 04276e5a..b92d5eb2 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -57,7 +57,7 @@ public class ScanLibraryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange ScanLibraryRequest request = _scanLibraryRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index b84eddcb..008a9e88 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -57,7 +57,7 @@ public class UpdateLibraryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 614fd2bb..17c86e3b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; using Microsoft.AspNetCore.Http; @@ -43,11 +44,13 @@ public class AddBookEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithBookResponse() { // Arrange + Guid libraryId = Guid.NewGuid(); AddBookRequest request = _addBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; BookResponse expectedResponse = _bookResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -84,13 +87,15 @@ public class AddBookEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); AddBookRequest request = _addBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -98,7 +103,7 @@ public class AddBookEndpointTests // Assert await _mockHandler.Received(1).HandleAsync( Arg.Is(command => - command.LibraryId == request.LibraryId && + command.LibraryId == libraryId.ToString() && command.Path == request.Path), Arg.Is(cancellationToken)); } @@ -130,4 +135,70 @@ public class AddBookEndpointTests // Assert await Assert.ThrowsAnyAsync(() => operationTask); } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.Library.LibraryIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + + // 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("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithRawRouteValue() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullLibraryId() + { + // Arrange + AddBookRequest request = _addBookRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == null), + Arg.Is(cancellationToken)); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs index 5e024bed..656815a6 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBook; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; using Microsoft.AspNetCore.Http; @@ -27,7 +25,6 @@ public class GetBookEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetBookEndpoint _sut; - private readonly GetBookRequestFixture _getBookRequestFixture = new(); private readonly BookResponseFixture _bookResponseFixture = new(); /// @@ -36,21 +33,24 @@ public class GetBookEndpointTests public GetBookEndpointTests() { _mockHandler = Substitute.For>>(); - _sut = Factory.Create(_mockHandler); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse() { // Arrange - GetBookRequest request = _getBookRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; BookResponse expectedResponse = _bookResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert Ok okResult = Assert.IsType>(result); @@ -61,14 +61,17 @@ public class GetBookEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange - GetBookRequest request = _getBookRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemDetails = Assert.IsType(result); @@ -85,14 +88,17 @@ public class GetBookEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange - GetBookRequest request = _getBookRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - Error validationError = Error.Validation(description: "BookIdCannotBeEmpty"); + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemDetails = Assert.IsType(result); @@ -101,27 +107,68 @@ public class GetBookEndpointTests HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); Assert.Single(validationProblemDetails.Errors); Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetBookQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetBookQueryToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); - GetBookRequest request = _getBookRequestFixture.Create(id: bookId.ToString()); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - await _sut.ExecuteAsync(request, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(query => query.Id == bookId), + Arg.Is(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_bookResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null && query.BookId == null), Arg.Is(cancellationToken)); } @@ -129,7 +176,8 @@ public class GetBookEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetBookRequest request = _getBookRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -142,9 +190,11 @@ public class GetBookEndpointTests callInfo.Arg().ThrowIfCancellationRequested(); return Result.From(_bookResponseFixture.Create()); }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 3d3dc530..3a5c902b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; @@ -63,12 +64,12 @@ public class GetBooksEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found."); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); @@ -77,19 +78,18 @@ public class GetBooksEndpointTests // Assert ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); @@ -118,18 +118,20 @@ public class GetBooksEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksQueryToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); GetBooksRequest request = _getBooksRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync(Arg.Is(query => - query.Filter.LibraryId == request.LibraryId && - query.Filter.SearchTerm == request.SearchTerm && + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && query.SortBy == request.SortBy && query.SortOrder == request.SortOrder && query.PaginationData != null && @@ -138,6 +140,44 @@ public class GetBooksEndpointTests Arg.Is(cancellationToken)); } + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetBooksRequest request = _getBooksRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + [Fact] public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index 77e5847c..a6e5cd32 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; @@ -63,12 +64,12 @@ public class GetBooksLiteEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - Error expectedError = Error.NotFound("Book.NotFound", "The requested book was not found."); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); @@ -77,19 +78,18 @@ public class GetBooksLiteEndpointTests // Assert ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); Assert.Equal("application/problem+json", problemDetails.ContentType); - Assert.IsType(problemDetails.ProblemDetails); - - Assert.Equal("Book.NotFound", problemDetails.ProblemDetails.Title); - Assert.Equal("The requested book was not found.", problemDetails.ProblemDetails.Detail); - Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); - Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); - Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status); + Assert.Equal("General.Unauthorized", problemDetailsBody.Title); + Assert.Equal("NotAuthorized", problemDetailsBody.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetailsBody.Type); + Assert.NotNull(problemDetailsBody.Extensions["traceId"]); } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); @@ -118,18 +118,22 @@ public class GetBooksLiteEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetBooksLiteQueryToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync(Arg.Is(query => - query.Filter.LibraryId == request.LibraryId && - query.Filter.SearchTerm == request.SearchTerm && + query.LibraryId == libraryId.ToString() && + query.SearchTerm == request.SearchTerm && + query.FilterAlphaKey == request.FilterAlphaKey && + query.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker && query.SortBy == request.SortBy && query.SortOrder == request.SortOrder && query.PaginationData != null && @@ -138,6 +142,44 @@ public class GetBooksLiteEndpointTests Arg.Is(cancellationToken)); } + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithRawRouteValue() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId() + { + // Arrange + GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null), + Arg.Is(cancellationToken)); + } + [Fact] public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 5aaa7e12..0792f339 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingAvailability; using Microsoft.AspNetCore.Http; @@ -27,7 +25,6 @@ public class GetReadingAvailabilityEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetReadingAvailabilityEndpoint _sut; - private readonly GetReadingAvailabilityRequestFixture _getReadingAvailabilityRequestFixture = new(); private readonly ReadingAvailabilityResponseFixture _readingAvailabilityResponseFixture = new(); /// @@ -36,21 +33,24 @@ public class GetReadingAvailabilityEndpointTests public GetReadingAvailabilityEndpointTests() { _mockHandler = Substitute.For>>(); - _sut = Factory.Create(_mockHandler); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingAvailability() { // Arrange - GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null); + ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: true, errorCode: null); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert Ok okResult = Assert.IsType>(result); @@ -61,14 +61,17 @@ public class GetReadingAvailabilityEndpointTests public async Task ExecuteAsync_WhenBookIsNotAvailable_ShouldReturnOkResultWithUnavailableReadingAvailability() { // Arrange - GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled"); + ReadingAvailabilityResponse expectedResponse = _readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: false, errorCode: "ReaderDisabled"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert Ok okResult = Assert.IsType>(result); @@ -78,17 +81,20 @@ public class GetReadingAvailabilityEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange - GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemResult = Assert.IsType(result); @@ -98,22 +104,91 @@ public class GetReadingAvailabilityEndpointTests Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail); } + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + [Fact] public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingAvailabilityQueryToSender() { // Arrange - GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingAvailabilityResponse response = _readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(response)); + .Returns(Result.From(_readingAvailabilityResponseFixture.Create(bookId: bookId, libraryId: libraryId, isAvailable: true, errorCode: null))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - await _sut.ExecuteAsync(request, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(query => query.BookId == request.BookId), + Arg.Is(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingAvailabilityResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingAvailabilityResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null && query.BookId == null), Arg.Is(cancellationToken)); } @@ -121,7 +196,8 @@ public class GetReadingAvailabilityEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetReadingAvailabilityRequest request = _getReadingAvailabilityRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -132,11 +208,13 @@ public class GetReadingAvailabilityEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(_readingAvailabilityResponseFixture.Create(bookId: request.BookId, isAvailable: true, errorCode: null)); + return Result.From(_readingAvailabilityResponseFixture.Create()); }, info.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index 7d8bdbb2..1dea9a39 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingManifest; using Microsoft.AspNetCore.Http; @@ -27,7 +25,6 @@ public class GetReadingManifestEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetReadingManifestEndpoint _sut; - private readonly GetReadingManifestRequestFixture _getReadingManifestRequestFixture = new(); private readonly ReadingManifestResponseFixture _readingManifestResponseFixture = new(); /// @@ -36,21 +33,24 @@ public class GetReadingManifestEndpointTests public GetReadingManifestEndpointTests() { _mockHandler = Substitute.For>>(); - _sut = Factory.Create(_mockHandler); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingManifest() { // Arrange - GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; ReadingManifestResponse expectedResponse = _readingManifestResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert Ok okResult = Assert.IsType>(result); @@ -58,17 +58,20 @@ public class GetReadingManifestEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange - GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Reading.BookNotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemResult = Assert.IsType(result); @@ -78,22 +81,91 @@ public class GetReadingManifestEndpointTests Assert.Equal("BookNotFound", problemResult.ProblemDetails.Detail); } + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + [Fact] public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingManifestQueryToSender() { // Arrange - GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingManifestResponse response = _readingManifestResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(response)); + .Returns(Result.From(_readingManifestResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - await _sut.ExecuteAsync(request, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(query => query.BookId == request.BookId), + Arg.Is(query => query.LibraryId == libraryId.ToString() && query.BookId == bookId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingManifestResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == "not-a-library-guid" && query.BookId == "not-a-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingManifestResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null && query.BookId == null), Arg.Is(cancellationToken)); } @@ -101,7 +173,8 @@ public class GetReadingManifestEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetReadingManifestRequest request = _getReadingManifestRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -114,9 +187,11 @@ public class GetReadingManifestEndpointTests info.Arg().ThrowIfCancellationRequested(); return Result.From(_readingManifestResponseFixture.Create()); }, info.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); 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 4a1460b9..8afcb909 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 @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingResource; using Microsoft.AspNetCore.Http; @@ -27,7 +25,6 @@ public class GetReadingResourceEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetReadingResourceEndpoint _sut; - private readonly GetReadingResourceRequestFixture _getReadingResourceRequestFixture = new(); private readonly ReadingResourceDataDtoFixture _readingResourceDataDtoFixture = new(); /// @@ -36,21 +33,25 @@ public class GetReadingResourceEndpointTests public GetReadingResourceEndpointTests() { _mockHandler = Substitute.For>>(); - _sut = Factory.Create(_mockHandler); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] public async Task ExecuteAsync_WhenSuccessful_ShouldReturnBytesResultWithResourceData() { // Arrange - GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; ReadingResourceDataDto expectedResponse = _readingResourceDataDtoFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert FileContentHttpResult bytesResult = Assert.IsType(result); @@ -59,17 +60,21 @@ public class GetReadingResourceEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange - GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Reading.ResourceNotFound", "ResourceNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemResult = Assert.IsType(result); @@ -79,6 +84,36 @@ public class GetReadingResourceEndpointTests Assert.Equal("ResourceNotFound", problemResult.ProblemDetails.Detail); } + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + [Theory] [InlineData("image/png", "image/png")] // a non-svg image is inert content [InlineData("image/svg+xml", "application/octet-stream")] // an svg can be executed, so it is served as an opaque download @@ -95,14 +130,18 @@ public class GetReadingResourceEndpointTests public async Task ExecuteAsync_WhenServingAResource_ShouldUseTheSafeContentType(string mimeType, string expectedContentType) { // Arrange - GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; ReadingResourceDataDto response = new(Guid.NewGuid().ToByteArray(), mimeType); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(response)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert FileContentHttpResult bytesResult = Assert.IsType(result); @@ -115,18 +154,67 @@ public class GetReadingResourceEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingResourceQueryToSender() { // Arrange - GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingResourceDataDto response = _readingResourceDataDtoFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(response)); + .Returns(Result.From(_readingResourceDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; // Act - await _sut.ExecuteAsync(request, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(query => query.BookId == request.BookId && query.ResourceKey == request.ResourceKey), + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.BookId == bookId.ToString() && + query.ResourceKey == "cover-image"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingResourceDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.BookId == "not-a-guid" && + query.ResourceKey == "cover-image"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingResourceDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); + _sut.HttpContext.Request.RouteValues.Remove("resourceKey"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null && query.BookId == null && query.ResourceKey == null), Arg.Is(cancellationToken)); } @@ -134,7 +222,8 @@ public class GetReadingResourceEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetReadingResourceRequest request = _getReadingResourceRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -147,9 +236,12 @@ public class GetReadingResourceEndpointTests info.Arg().ThrowIfCancellationRequested(); return Result.From(_readingResourceDataDtoFixture.Create()); }, info.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["resourceKey"] = "cover-image"; // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs index b36af42e..98cbd36e 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSection/GetReadingSectionEndpointTests.cs @@ -1,11 +1,9 @@ #region ========================================================================= USING ===================================================================================== -using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; -using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; -using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Reading.GetReadingSection; using Microsoft.AspNetCore.Http; @@ -27,7 +25,6 @@ public class GetReadingSectionEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetReadingSectionEndpoint _sut; - private readonly GetReadingSectionRequestFixture _getReadingSectionRequestFixture = new(); private readonly ReadingSectionDtoFixture _readingSectionDtoFixture = new(); /// @@ -36,21 +33,25 @@ public class GetReadingSectionEndpointTests public GetReadingSectionEndpointTests() { _mockHandler = Substitute.For>>(); - _sut = Factory.Create(_mockHandler); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithReadingSection() { // Arrange - GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); + ReadingSectionDto expectedResponse = _readingSectionDtoFixture.Create(locationRef: "chapter-1"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1"; // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert Ok okResult = Assert.IsType>(result); @@ -58,17 +59,21 @@ public class GetReadingSectionEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange - GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Reading.SectionNotFound", "SectionNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1"; // Act - IResult result = await _sut.ExecuteAsync(request, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemResult = Assert.IsType(result); @@ -78,22 +83,101 @@ public class GetReadingSectionEndpointTests Assert.Equal("SectionNotFound", problemResult.ProblemDetails.Detail); } + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1"; + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + [Fact] public async Task ExecuteAsync_WhenCalled_ShouldSendGetReadingSectionQueryToSender() { // Arrange - GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; - ReadingSectionDto response = _readingSectionDtoFixture.Create(locationRef: request.LocationRef); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(response)); + .Returns(Result.From(_readingSectionDtoFixture.Create(locationRef: "chapter-1"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1"; // Act - await _sut.ExecuteAsync(request, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(query => query.BookId == request.BookId && query.LocationRef == request.LocationRef), + Arg.Is(query => + query.LibraryId == libraryId.ToString() && + query.BookId == bookId.ToString() && + query.LocationRef == "chapter-1"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendQueryWithRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingSectionDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; + _sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1"; + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == "not-a-library-guid" && + query.BookId == "not-a-guid" && + query.LocationRef == "chapter-1"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_readingSectionDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); + _sut.HttpContext.Request.RouteValues.Remove("locationRef"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == null && query.BookId == null && query.LocationRef == null), Arg.Is(cancellationToken)); } @@ -101,7 +185,8 @@ public class GetReadingSectionEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange - GetReadingSectionRequest request = _getReadingSectionRequestFixture.Create(); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -112,11 +197,14 @@ public class GetReadingSectionEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(_readingSectionDtoFixture.Create(locationRef: request.LocationRef)); + return Result.From(_readingSectionDtoFixture.Create()); }, info.Arg())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["locationRef"] = "chapter-1"; // Act - Task operationTask = _sut.ExecuteAsync(request, cts.Token); + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs index ce8b42b6..748b777c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBook/UpdateBookEndpointTests.cs @@ -5,6 +5,7 @@ using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBook; using Microsoft.AspNetCore.Http; @@ -24,7 +25,7 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookEndpointTests { - private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly Lumina.Application.Common.CQRS.ICommandHandler> _mockHandler; private readonly UpdateBookEndpoint _sut; private readonly UpdateBookRequestFixture _updateBookRequestFixture = new(); private readonly BookResponseFixture _bookResponseFixture = new(); @@ -34,7 +35,7 @@ public class UpdateBookEndpointTests /// public UpdateBookEndpointTests() { - _mockHandler = Substitute.For>>(); + _mockHandler = Substitute.For>>(); _sut = Factory.Create(_mockHandler); } @@ -42,13 +43,15 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookResponse() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; BookResponse expectedResponse = _bookResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); - ConfigureRequest(routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -62,13 +65,15 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); - ConfigureRequest(routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -88,13 +93,15 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - Error validationError = Error.Validation(description: "BookIdCannotBeEmpty"); + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(validationError); - ConfigureRequest(routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -106,21 +113,24 @@ public class UpdateBookEndpointTests HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); Assert.Single(validationProblemDetails.Errors); Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); } [Fact] - public async Task ExecuteAsync_WhenCalledWithMatchingRouteId_ShouldSendUpdateBookCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -128,7 +138,8 @@ public class UpdateBookEndpointTests // Assert await _mockHandler.Received(1).HandleAsync( Arg.Is(command => - command.Id == routeId && + command.LibraryId == libraryId.ToString() && + command.BookId == routeId.ToString() && command.Metadata == request.Metadata && command.Format == request.Format && command.Edition == request.Edition && @@ -140,80 +151,42 @@ public class UpdateBookEndpointTests } [Fact] - public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldSendCommandWithRouteId() - { - // Arrange - Guid routeId = Guid.NewGuid(); - Guid bodyId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: bodyId); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(routeId.ToString()); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == routeId && command.Id != bodyId), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId() + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() { // Arrange UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest("not-a-guid"); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(command => command.LibraryId == "not-a-library-guid" && command.BookId == "not-a-guid"), Arg.Is(cancellationToken)); } [Fact] - public async Task ExecuteAsync_WhenRouteIdIsEmpty_ShouldSendCommandWithEmptyBookId() + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() { // Arrange UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(string.Empty); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); // Act await _sut.ExecuteAsync(request, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == Guid.Empty), - Arg.Is(cancellationToken)); - } - - [Fact] - public async Task ExecuteAsync_WhenRouteIdIsMissing_ShouldSendCommandWithEmptyBookId() - { - // Arrange - UpdateBookRequest request = _updateBookRequestFixture.Create(); - CancellationToken cancellationToken = CancellationToken.None; - _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequestWithoutId(); - - // Act - await _sut.ExecuteAsync(request, cancellationToken); - - // Assert - await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.Id == Guid.Empty), + Arg.Is(command => command.LibraryId == null && command.BookId == null), Arg.Is(cancellationToken)); } @@ -221,8 +194,9 @@ public class UpdateBookEndpointTests public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid routeId = Guid.NewGuid(); - UpdateBookRequest request = _updateBookRequestFixture.Create(id: routeId); + UpdateBookRequest request = _updateBookRequestFixture.Create(); CancellationTokenSource cts = new(); TaskCompletionSource operationStarted = new(); TaskCompletionSource cancellationRequested = new(); @@ -235,7 +209,8 @@ public class UpdateBookEndpointTests callInfo.Arg().ThrowIfCancellationRequested(); return Result.From(_bookResponseFixture.Create()); }, callInfo.Arg())); - ConfigureRequest(routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); @@ -246,21 +221,4 @@ public class UpdateBookEndpointTests // Assert await Assert.ThrowsAnyAsync(() => operationTask); } - - /// - /// Sets the id route value the endpoint reads the book Id from. - /// - /// The raw route value of the book Id. - private void ConfigureRequest(string routeId) - { - _sut.HttpContext.Request.RouteValues["id"] = routeId; - } - - /// - /// Leaves the id route value unset. - /// - private void ConfigureRequestWithoutId() - { - _sut.HttpContext.Request.RouteValues.Remove("id"); - } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs index ccc440d2..04bd9362 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -1,6 +1,9 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.UpdateBookCover; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; using Microsoft.AspNetCore.Http; @@ -22,110 +25,178 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten [ExcludeFromCodeCoverage] public class UpdateBookCoverEndpointTests { - private readonly Application.Common.CQRS.ICommandHandler> _mockHandler; + private readonly ICommandHandler> _mockHandler; private readonly UpdateBookCoverEndpoint _sut; + private readonly UpdateBookCoverResponseFixture _updateBookCoverResponseFixture = new(); /// /// Initializes a new instance of the class. /// public UpdateBookCoverEndpointTests() { - _mockHandler = Substitute.For>>(); - _sut = Factory.Create(_mockHandler); + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); } [Fact] public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithCoverPath() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; string expectedPath = "/media/books/cover.jpg"; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(expectedPath)); - ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + .Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: expectedPath))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); // Act - IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert - Ok okResult = Assert.IsType>(result); - Assert.Equal(expectedPath, okResult.Value); + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedPath, okResult.Value.CoverPath); } [Fact] - public async Task ExecuteAsync_WhenCalledWithValidRouteIdAndFile_ShouldSendUpdateBookCoverCommand() + public async Task ExecuteAsync_WhenCalledWithValidRouteIdsAndFile_ShouldSendUpdateBookCoverCommandToSender() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From("/media/books/cover.jpg")); - ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + .Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); // Act - await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( Arg.Is(command => - command.BookId == bookId && + command.LibraryId == libraryId.ToString() && + command.BookId == bookId.ToString() && command.Cover != null && command.FileName == "cover.jpg"), Arg.Is(cancellationToken)); } [Fact] - public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldSendCommandWithEmptyBookId() + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues() { // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From("/media/books/cover.jpg")); - ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg"); + .Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; + _sut.HttpContext.Request.RouteValues["bookId"] = "not-a-guid"; + ConfigureForm([1, 2, 3], "cover.jpg"); // Act - await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.BookId == Guid.Empty && command.Cover != null), - Arg.Any()); + Arg.Is(command => command.LibraryId == "not-a-library-guid" && command.BookId == "not-a-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIds() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg"))); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.LibraryId == null && command.BookId == null), + Arg.Is(cancellationToken)); } [Fact] public async Task ExecuteAsync_WhenFormHasNoFiles_ShouldSendCommandWithNullCover() { // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From("/media/books/cover.jpg")); - ConfigureRequestWithoutFiles(bookId); + .Returns(Result.From(_updateBookCoverResponseFixture.Create(coverPath: "/media/books/cover.jpg"))); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + IFormCollection form = new FormCollection([]); + _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; + _sut.HttpContext.Features.Set(new FormFeature(form)); // Act - IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert - Assert.IsType>(result); + Assert.IsType>(result); await _mockHandler.Received(1).HandleAsync( - Arg.Is(command => command.BookId == bookId && command.Cover == null && command.FileName == null), + Arg.Is(command => command.BookId == bookId.ToString() && command.Cover == null && command.FileName == null), Arg.Any()); } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + Error validationError = Errors.WrittenContent.BookIdCannotBeEmpty; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(validationError); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "BookIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() + { + // Arrange + Guid libraryId = Guid.NewGuid(); Guid bookId = Guid.NewGuid(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); - ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + ConfigureForm([1, 2, 3], "cover.jpg"); // Act - IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); // Assert ProblemHttpResult problemDetails = Assert.IsType(result); @@ -138,14 +209,8 @@ public class UpdateBookCoverEndpointTests Assert.NotNull(problemDetailsBody.Extensions["traceId"]); } - private void ConfigureRequest(Guid bookId, byte[] content, string fileName) + private void ConfigureForm(byte[] content, string fileName) { - ConfigureRequest(bookId.ToString(), content, fileName); - } - - private void ConfigureRequest(string bookId, byte[] content, string fileName) - { - _sut.HttpContext.Request.RouteValues["id"] = bookId; MemoryStream coverStream = new(content); IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName); FormFileCollection files = [formFile]; @@ -153,12 +218,4 @@ public class UpdateBookCoverEndpointTests _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; _sut.HttpContext.Features.Set(new FormFeature(form)); } - - private void ConfigureRequestWithoutFiles(Guid bookId) - { - _sut.HttpContext.Request.RouteValues["id"] = bookId.ToString(); - IFormCollection form = new FormCollection([]); - _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; - _sut.HttpContext.Features.Set(new FormFeature(form)); - } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index e95176ec..e042e49c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -53,7 +53,7 @@ public class CheckInitializationEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendCheckInitializationQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index 4ad1b481..57a1285b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -58,7 +58,7 @@ public class SetupApplicationEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnProblemResult() { // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs index 88583a22..28d4742a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -63,7 +63,7 @@ public class GetLibraryArtworkProvidersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs index fa0871ad..758d5c75 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryBookReaders/GetLibraryBookReadersEndpointTests.cs @@ -59,7 +59,7 @@ public class GetLibraryBookReadersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange GetLibraryBookReadersRequest request = _getLibraryBookReadersRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index 8dd41075..619bdbdc 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -63,7 +63,7 @@ public class GetLibraryMetadataProvidersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetLibraryMetadataProvidersRequest request = _getLibraryMetadataProvidersRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index 6277cfcb..ed7d867b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -62,7 +62,7 @@ public class GetPluginSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index 416e7f6b..b44af948 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -56,7 +56,7 @@ public class GetPluginsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -81,7 +81,7 @@ public class GetPluginsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetPluginsQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPluginsQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs index 272e253b..8a5d82fd 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -54,7 +54,7 @@ public class ReorderLibraryArtworkProvidersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs index 88b8e0d3..cfb8c07a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -54,7 +54,7 @@ public class ReorderLibraryMetadataProvidersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs index 4668185b..6a898b1f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -53,7 +53,7 @@ public class SetLibraryArtworkProviderEnabledEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs index 757db7bc..0eec00c5 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryBookReaderEnabled/SetLibraryBookReaderEnabledEndpointTests.cs @@ -53,7 +53,7 @@ public class SetLibraryBookReaderEnabledEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs index f357a42c..97f1e840 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -53,7 +53,7 @@ public class SetLibraryMetadataProviderEnabledEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 5a44c4ff..a55c7970 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -53,7 +53,7 @@ public class UpdatePluginSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs index 4043ca70..4be9cd56 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/AddScheduledJob/AddScheduledJobEndpointTests.cs @@ -66,7 +66,7 @@ public class AddScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create(); @@ -86,7 +86,7 @@ public class AddScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToSender() { // Arrange AddScheduledJobRequest request = _addScheduledJobRequestFixture.Create( diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs index 3be065a6..f67f37e1 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/FireScheduledJob/FireScheduledJobEndpointTests.cs @@ -66,7 +66,7 @@ public class FireScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); @@ -86,7 +86,7 @@ public class FireScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); @@ -103,7 +103,7 @@ public class FireScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToSender() { // Arrange FireScheduledJobRequest request = _fireScheduledJobRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs index f0873f97..b391855f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobHistory/GetScheduledJobHistoryEndpointTests.cs @@ -61,7 +61,7 @@ public class GetScheduledJobHistoryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsUnauthorizedError_ShouldReturnProblemResult() { // Arrange GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(); @@ -78,7 +78,7 @@ public class GetScheduledJobHistoryEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedQueryToSender() { // Arrange GetScheduledJobHistoryRequest request = _getScheduledJobHistoryRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs index 516be193..069584b0 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetScheduledJobs/GetScheduledJobsEndpointTests.cs @@ -56,7 +56,7 @@ public class GetScheduledJobsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsUnauthorizedError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -72,7 +72,7 @@ public class GetScheduledJobsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs index eb46fc16..d2545575 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/GetSchedulerDisplayPreferences/GetSchedulerDisplayPreferencesEndpointTests.cs @@ -54,7 +54,7 @@ public class GetSchedulerDisplayPreferencesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsUnauthorizedError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -70,7 +70,7 @@ public class GetSchedulerDisplayPreferencesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs index d9d0d9b3..fc48a2af 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/RemoveScheduledJob/RemoveScheduledJobEndpointTests.cs @@ -55,7 +55,7 @@ public class RemoveScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); @@ -73,7 +73,7 @@ public class RemoveScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); @@ -90,7 +90,7 @@ public class RemoveScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToSender() { // Arrange RemoveScheduledJobRequest request = _removeScheduledJobRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs index 77f70842..60d2bd45 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StartScheduledJob/StartScheduledJobEndpointTests.cs @@ -61,7 +61,7 @@ public class StartScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult() { // Arrange StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); @@ -79,7 +79,7 @@ public class StartScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); @@ -96,7 +96,7 @@ public class StartScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToSender() { // Arrange StartScheduledJobRequest request = _startScheduledJobRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs index 80c13a69..6f533875 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/StopScheduledJob/StopScheduledJobEndpointTests.cs @@ -61,7 +61,7 @@ public class StopScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); @@ -79,7 +79,7 @@ public class StopScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); @@ -96,7 +96,7 @@ public class StopScheduledJobEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToSender() { // Arrange StopScheduledJobRequest request = _stopScheduledJobRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs index 26a5f532..b5889653 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Scheduling/UpdateSchedulerDisplayPreferences/UpdateSchedulerDisplayPreferencesEndpointTests.cs @@ -55,7 +55,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); @@ -73,7 +73,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnProblemResult() { // Arrange UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); @@ -90,7 +90,7 @@ public class UpdateSchedulerDisplayPreferencesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendMappedCommandToSender() { // Arrange UpdateSchedulerDisplayPreferencesRequest request = _updateSchedulerDisplayPreferencesRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs index 18173544..d04fc0b4 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/DeleteTheme/DeleteThemeEndpointTests.cs @@ -129,7 +129,7 @@ public class DeleteThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); @@ -155,7 +155,7 @@ public class DeleteThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteThemeCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteThemeCommandToSender() { // Arrange DeleteThemeRequest request = _deleteThemeRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs index cc96569a..c5a4ab5f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/RestoreTheme/RestoreThemeEndpointTests.cs @@ -129,7 +129,7 @@ public class RestoreThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); @@ -155,7 +155,7 @@ public class RestoreThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendRestoreThemeCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendRestoreThemeCommandToSender() { // Arrange RestoreThemeRequest request = _restoreThemeRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 301621b3..5f23d85e 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Management/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -110,7 +110,7 @@ public class SetCurrentThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); @@ -136,7 +136,7 @@ public class SetCurrentThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendSetCurrentThemeCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendSetCurrentThemeCommandToSender() { // Arrange SetCurrentThemeRequest request = _setCurrentThemeRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs index e9cedbb9..ad79074d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetCurrentTheme/GetCurrentThemeEndpointTests.cs @@ -79,7 +79,7 @@ public class GetCurrentThemeEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetCurrentThemeQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetCurrentThemeQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs index 97a35cd2..4110789f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeArchive/GetThemeArchiveEndpointTests.cs @@ -87,7 +87,7 @@ public class GetThemeArchiveEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); @@ -113,7 +113,7 @@ public class GetThemeArchiveEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeArchiveQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeArchiveQueryToSender() { // Arrange GetThemeArchiveRequest request = _getThemeArchiveRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs index 66443e2f..4064fc76 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeAsset/GetThemeAssetEndpointTests.cs @@ -86,7 +86,7 @@ public class GetThemeAssetEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); @@ -112,7 +112,7 @@ public class GetThemeAssetEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeAssetQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeAssetQueryToSender() { // Arrange GetThemeAssetRequest request = _getThemeAssetRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs index ab0e92d8..4da05cfc 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeSettings/GetThemeSettingsEndpointTests.cs @@ -79,7 +79,7 @@ public class GetThemeSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeSettingsQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeSettingsQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs index 80a3de9e..a0adc93b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointTests.cs @@ -84,7 +84,7 @@ public class GetThemeTemplateEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); @@ -110,7 +110,7 @@ public class GetThemeTemplateEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeTemplateQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemeTemplateQueryToSender() { // Arrange GetThemeTemplateRequest request = _getThemeTemplateRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs index 7af2cec2..bae448f8 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Themes/Queries/GetThemes/GetThemesEndpointTests.cs @@ -81,7 +81,7 @@ public class GetThemesEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemesQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetThemesQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index 3cb05f37..8079a207 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -57,7 +57,7 @@ public class ChangePasswordEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange ChangePasswordRequest request = _changePasswordRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs index b3d56177..e02894d3 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs @@ -57,7 +57,7 @@ public class GetUsersEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index dc2c2d7d..6169f0f1 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -58,7 +58,7 @@ public class LoginEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange LoginRequest request = _loginRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index b1a1bf19..11b80de7 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -57,7 +57,7 @@ public class RecoverPasswordEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index 1f159251..5fab6281 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -58,7 +58,7 @@ public class RegisterEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs index b9a3303a..5f244eec 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs @@ -65,7 +65,7 @@ public class GetAuthorizationEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsUnauthorizedError_ShouldReturnProblemResult() { // Arrange GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs index a8d2aa73..45e0b92f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -64,7 +64,7 @@ public class GetUserPermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs index bf327964..6a8abd4f 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -58,7 +58,7 @@ public class GetUserRoleEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange GetUserRoleRequest request = _getUserRoleRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs index ab154a3b..3f523e15 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -63,7 +63,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index b5f947be..78554143 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -54,7 +54,7 @@ public class GetUserSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() { // Arrange CancellationToken cancellationToken = CancellationToken.None; @@ -76,7 +76,7 @@ public class GetUserSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendGetUserSettingsQueryToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendGetUserSettingsQueryToSender() { // Arrange CancellationToken cancellationToken = CancellationToken.None; diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index b4054779..4b1b10a3 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -53,7 +53,7 @@ public class UpdateUserSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() { // Arrange UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); @@ -75,7 +75,7 @@ public class UpdateUserSettingsEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToSender() { // Arrange UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs index 72e3e1a8..0b91d09d 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs @@ -67,7 +67,7 @@ public class ApiHttpClientTests Assert.Equal(HttpStatusCode.UnprocessableEntity, exception.HttpStatusCode); Assert.NotNull(exception.ProblemDetails); Assert.Equal("General.Validation", exception.ProblemDetails!.Title); - Assert.Equal(422, exception.ProblemDetails.Status); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, exception.ProblemDetails.Status); Assert.Equal("OneOrMoreValidationErrorsOccurred", exception.ProblemDetails.Detail); } @@ -111,7 +111,7 @@ public class ApiHttpClientTests SuccessResponse result = await sut.PostAsync("auth/login", new { username = "testuser" }, CancellationToken.None); // Assert - Assert.True(result.Success); + Assert.True(result.IsSuccess); Assert.Equal(HttpMethod.Post, messageHandler.Requests[0].Method); Assert.Equal("http://localhost:5214/api/v1/auth/login", messageHandler.Requests[0].RequestUri!.ToString()); Assert.Contains("testuser", messageHandler.RequestBodies[0]); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs index 8c588a76..1b99c1bc 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Services/ThemeCachePreferenceServiceTests.cs @@ -37,7 +37,7 @@ public class ThemeCachePreferenceServiceTests Guid userId = Guid.NewGuid(); // Act - bool result = await _sut.GetAsync(userId, defaultValue: true, CancellationToken.None); + bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: true, CancellationToken.None); // Assert Assert.True(result); @@ -50,7 +50,7 @@ public class ThemeCachePreferenceServiceTests Guid userId = Guid.NewGuid(); // Act - bool result = await _sut.GetAsync(userId, defaultValue: false, CancellationToken.None); + bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: false, CancellationToken.None); // Assert Assert.False(result); @@ -64,7 +64,7 @@ public class ThemeCachePreferenceServiceTests // Act await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None); - bool result = await _sut.GetAsync(userId, defaultValue: false, CancellationToken.None); + bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: false, CancellationToken.None); // Assert Assert.True(result); @@ -79,7 +79,7 @@ public class ThemeCachePreferenceServiceTests // Act await _sut.SetAsync(userId, isEnabled: true, CancellationToken.None); await _sut.SetAsync(userId, isEnabled: false, CancellationToken.None); - bool result = await _sut.GetAsync(userId, defaultValue: true, CancellationToken.None); + bool result = await _sut.GetAsync(userId, isCachingEnabledByDefault: true, CancellationToken.None); // Assert Assert.False(result); @@ -94,8 +94,8 @@ public class ThemeCachePreferenceServiceTests // Act await _sut.SetAsync(firstUserId, isEnabled: true, CancellationToken.None); - bool firstUserResult = await _sut.GetAsync(firstUserId, defaultValue: false, CancellationToken.None); - bool secondUserResult = await _sut.GetAsync(secondUserId, defaultValue: false, CancellationToken.None); + bool firstUserResult = await _sut.GetAsync(firstUserId, isCachingEnabledByDefault: false, CancellationToken.None); + bool secondUserResult = await _sut.GetAsync(secondUserId, isCachingEnabledByDefault: false, CancellationToken.None); // Assert Assert.True(firstUserResult); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs index cd7c6294..49ede696 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -43,7 +43,7 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenApiReturnsDirectories_ShouldReturnSuccessJsonWithDirectories() { // Arrange - GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: true); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", shouldIncludeHiddenElements: true); DirectoryDto[] expectedDirectories = [_directoryDtoFixture.Create(path: "/media/books", name: "books")]; _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(expectedDirectories); @@ -53,7 +53,7 @@ public class GetDirectoriesEndpointTests string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=True"; + string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&shouldIncludeHiddenElements=True"; await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); using JsonDocument jsonDocument = JsonDocument.Parse(body); Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); @@ -64,7 +64,7 @@ public class GetDirectoriesEndpointTests public async Task ExecuteAsync_WhenCalledWithoutHiddenElements_ShouldRequestWithoutHiddenElementsFlag() { // Arrange - GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: false); + GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", shouldIncludeHiddenElements: false); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns([]); @@ -72,7 +72,7 @@ public class GetDirectoriesEndpointTests await _sut.ExecuteAsync(request, CancellationToken.None); // Assert - string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&includeHiddenElements=False"; + string expectedEndpoint = $"{ApiRoutes.Directories.GET_DIRECTORIES}?path={Uri.EscapeDataString(request.Path!)}&shouldIncludeHiddenElements=False"; await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs index f2f5755b..296bb1e9 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBookDetails/GetBookDetailsEndpointTests.cs @@ -44,7 +44,7 @@ public class GetBookDetailsEndpointTests { // Arrange GetBookRequest request = _getBookRequestFixture.Create(); - BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id)); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId)); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(expectedBook); @@ -53,7 +53,7 @@ public class GetBookDetailsEndpointTests // Assert await _mockApiHttpClient.Received(1).GetAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{id}", request.Id)), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.GET_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId)), Arg.Any()); } @@ -62,7 +62,7 @@ public class GetBookDetailsEndpointTests { // Arrange GetBookRequest request = _getBookRequestFixture.Create(); - BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.Id)); + BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(id: Guid.Parse(request.BookId)); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(expectedBook); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs index dabae867..07f2c8e1 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -63,8 +63,7 @@ public class GetLibraryItemsEndpointTests // Assert await _mockApiHttpClient.Received(1).GetAsync( Arg.Is(endpoint => - endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && - endpoint.Contains($"libraryId={request.LibraryId}") && + endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) && endpoint.Contains("currentPage=2") && endpoint.Contains("perPage=48") && endpoint.Contains("searchTerm=the%20hobbit") && @@ -89,8 +88,8 @@ public class GetLibraryItemsEndpointTests // Assert await _mockApiHttpClient.Received(1).GetAsync( Arg.Is(endpoint => - endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && - endpoint.EndsWith($"libraryId={request.LibraryId}&shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) && + endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE.Replace("{libraryId}", request.LibraryId.ToString()), StringComparison.OrdinalIgnoreCase) && + endpoint.EndsWith("?shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) && !endpoint.Contains("currentPage=") && !endpoint.Contains("searchTerm=") && !endpoint.Contains("sortBy=")), 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 62b4b8b4..6e2a9122 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 @@ -45,7 +45,7 @@ public class GetReadingAvailabilityEndpointTests // Arrange GetBookReadingAvailabilityRequest request = _requestFixture.Create(); ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true); - _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(availability); // Act @@ -64,7 +64,7 @@ public class GetReadingAvailabilityEndpointTests // Arrange GetBookReadingAvailabilityRequest request = _requestFixture.Create(); ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: false, errorCode: "ReaderDisabled"); - _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(availability); // Act @@ -81,15 +81,15 @@ public class GetReadingAvailabilityEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldRequestReadingAvailabilityFromApi() { // Arrange - GetBookReadingAvailabilityRequest request = new(BookId: Guid.NewGuid()); + GetBookReadingAvailabilityRequest request = _requestFixture.Create(); ReadingAvailabilityDto availability = _readingAvailabilityDtoFixture.Create(bookId: request.BookId, isAvailable: true); - _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(availability); // Act await _sut.ExecuteAsync(request, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{bookId}", request.BookId.ToString()), Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Books.GET_BOOK_READING_AVAILABILITY.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()); } } 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 a6ca715c..fbae8781 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 @@ -49,7 +49,7 @@ public class GetReadingManifestEndpointTests // Arrange GetBookReadingManifestRequest request = _requestFixture.Create(); ReadingManifestDto manifest = _readingManifestDtoFixture.Create(); - _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(manifest); // Act @@ -119,13 +119,13 @@ public class GetReadingManifestEndpointTests // Arrange GetBookReadingManifestRequest request = _requestFixture.Create(); ReadingManifestDto manifest = _readingManifestDtoFixture.Create(); - _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any()) + _mockApiHttpClient.GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()) .Returns(manifest); // Act await _sut.ExecuteAsync(request, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{bookId}", request.BookId.ToString()), Arg.Any()); + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Books.GET_BOOK_READING_MANIFEST.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", request.BookId.ToString()), Arg.Any()); } } 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 21dc7f3a..4e9cb830 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 @@ -65,6 +65,7 @@ public class GetReadingResourceEndpointTests _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) .Returns(blob); string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_RESOURCE + .Replace("{libraryId}", request.LibraryId.ToString()) .Replace("{bookId}", request.BookId.ToString()) .Replace("{resourceKey}", Uri.EscapeDataString(request.ResourceKey)); 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 dd7d29cf..81f0bb18 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 @@ -67,6 +67,7 @@ public class GetReadingSectionEndpointTests _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(section); string expectedEndpoint = ApiRoutes.Books.GET_BOOK_READING_SECTION + .Replace("{libraryId}", request.LibraryId.ToString()) .Replace("{bookId}", request.BookId.ToString()) .Replace("{locationRef}", Uri.EscapeDataString(request.LocationRef)); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index e52f6031..2d338d39 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -55,8 +55,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == routeId), Arg.Any()); } @@ -67,7 +67,7 @@ public class SaveBookEndpointTests string routeId = Guid.NewGuid().ToString(); string bodyId = Guid.NewGuid().ToString(); UpdateBookRequest request = _updateBookRequestFixture.Create(); - request.Id = bodyId; + request.BookId = bodyId; BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create(); _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(expectedBook); @@ -78,8 +78,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", routeId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == routeId && forwardedRequest.Id != bodyId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", routeId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == routeId && forwardedRequest.BookId != bodyId), Arg.Any()); } @@ -100,8 +100,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == expectedId), Arg.Any()); } @@ -121,8 +121,8 @@ public class SaveBookEndpointTests // Assert await _mockApiHttpClient.Received(1).PutAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{id}", expectedId)), - Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.Id == expectedId), + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{bookId}", expectedId)), + Arg.Is(forwardedRequest => forwardedRequest == request && forwardedRequest.BookId == expectedId), Arg.Any()); } @@ -153,7 +153,7 @@ public class SaveBookEndpointTests /// The raw route value of the book Id. private void ConfigureRequest(string routeId) { - _sut.HttpContext.Request.RouteValues["id"] = routeId; + _sut.HttpContext.Request.RouteValues["bookId"] = routeId; } /// diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs index 3c1cce1c..3ae85f70 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpointTests.cs @@ -1,8 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; +using Lumina.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; @@ -26,6 +28,8 @@ public class UpdateBookCoverEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly UpdateBookCoverEndpoint _sut; + private readonly UpdateBookCoverDtoFixture _updateBookCoverDtoFixture = new(); + private static readonly Guid s_libraryId = Guid.NewGuid(); /// /// Initializes a new instance of the class. @@ -41,16 +45,16 @@ public class UpdateBookCoverEndpointTests { // Arrange Guid bookId = Guid.NewGuid(); - _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns("/media/books/cover.jpg"); + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.jpg")); ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PutMultipartAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", bookId.ToString())), + await _mockApiHttpClient.Received(1).PutMultipartAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())), Arg.Any(), Arg.Is(fileName => fileName == "cover.jpg"), Arg.Is(fieldName => fieldName == "cover"), @@ -61,16 +65,16 @@ public class UpdateBookCoverEndpointTests public async Task ExecuteAsync_WhenRouteIdIsNotParseable_ShouldUploadCoverWithEmptyBookId() { // Arrange - _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns("/media/books/cover.jpg"); + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_updateBookCoverDtoFixture.Create(coverPath: "/media/books/cover.jpg")); ConfigureRequest("not-a-guid", [1, 2, 3], "cover.jpg"); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); // Assert - await _mockApiHttpClient.Received(1).PutMultipartAsync( - Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{id}", Guid.Empty.ToString())), + await _mockApiHttpClient.Received(1).PutMultipartAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", Guid.Empty.ToString())), Arg.Any(), Arg.Any(), Arg.Any(), @@ -83,8 +87,8 @@ public class UpdateBookCoverEndpointTests // Arrange Guid bookId = Guid.NewGuid(); string expectedPath = "/media/books/cover.jpg"; - _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(expectedPath); + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath)); ConfigureRequest(bookId, [1, 2, 3], "cover.jpg"); // Act @@ -98,20 +102,57 @@ public class UpdateBookCoverEndpointTests } [Fact] - public async Task ExecuteAsync_WhenFormHasNoFile_ShouldReturnBadRequestProblem() + public async Task ExecuteAsync_WhenFormHasNoFile_ShouldForwardRequestWithoutFileToApi() { // Arrange Guid bookId = Guid.NewGuid(); + string expectedPath = "/media/books/cover.jpg"; + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath)); ConfigureRequestWithoutFiles(bookId); // Act IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - ProblemHttpResult problemDetails = Assert.IsType(result); - Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.StatusCode); - Assert.Equal("The uploaded cover image is missing.", problemDetails.ProblemDetails.Detail); - await _mockApiHttpClient.DidNotReceive().PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockApiHttpClient.Received(1).PutMultipartAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())), + Arg.Is(stream => stream == null), + Arg.Is(fileName => fileName == null), + Arg.Is(fieldName => fieldName == "cover"), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestIsNotMultipart_ShouldForwardRequestWithoutFileToApi() + { + // Arrange + Guid bookId = Guid.NewGuid(); + string expectedPath = "/media/books/cover.jpg"; + _mockApiHttpClient.PutMultipartAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_updateBookCoverDtoFixture.Create(coverPath: expectedPath)); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}"); + _sut.HttpContext.Request.ContentType = "application/json"; + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PutMultipartAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Books.UPDATE_BOOK_COVER.Replace("{libraryId}", s_libraryId.ToString()).Replace("{bookId}", bookId.ToString())), + Arg.Is(stream => stream == null), + Arg.Is(fileName => fileName == null), + Arg.Is(fieldName => fieldName == "cover"), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPath, jsonDocument.RootElement.GetProperty("data").GetString()); } private void ConfigureRequest(Guid bookId, byte[] content, string fileName) @@ -121,7 +162,8 @@ public class UpdateBookCoverEndpointTests private void ConfigureRequest(string bookId, byte[] content, string fileName) { - _sut.HttpContext.Request.RouteValues["id"] = bookId; + _sut.HttpContext.Request.RouteValues["bookId"] = bookId; + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}"); MemoryStream coverStream = new(content); IFormFile formFile = new FormFile(coverStream, 0, content.Length, "cover", fileName); FormFileCollection files = [formFile]; @@ -132,7 +174,8 @@ public class UpdateBookCoverEndpointTests private void ConfigureRequestWithoutFiles(Guid bookId) { - _sut.HttpContext.Request.RouteValues["id"] = bookId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = bookId.ToString(); + _sut.HttpContext.Request.QueryString = new QueryString($"?libraryId={s_libraryId}"); IFormCollection form = new FormCollection([]); _sut.HttpContext.Request.ContentType = "multipart/form-data; boundary=----test"; _sut.HttpContext.Features.Set(new FormFeature(form));
@_localizer["ContributorName"]@_localizer["RoleName"]@_localizer["RoleCategory"]@_localizer["ContributorName"]@_localizer["Role"]
-
+
- -
${buildRowCombobox(contributorCategoryOptions, 'Author')}${buildRowCombobox(contributorRoleOptions, 'Author')} ${jsLocalizedStrings.remove}