From ea6eb9f796acec78a70b5d425465042ada5e84fa Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 17 Sep 2026 13:30:48 -0700 Subject: [PATCH] Refactors the book, artist, and album slices across the stack --- .../audio-library/music-library/Api.Albums.md | 688 +++-- .../music-library/Api.Artists.md | 679 ++++- .../audio-library/music-library/Api.Tracks.md | 147 +- .../domain/Aggregates.AudioLibrary.md | 14 +- .../Aggregates.WrittenContentLibrary.md | 4 +- .../music-library/albums/AddAlbum.http | 13 +- .../music-library/albums/DeleteAlbum.http | 2 +- .../music-library/albums/GetAlbum.http | 2 +- .../music-library/albums/GetAlbumTracks.http | 2 +- .../albums/GetAlbumTracksLite.http | 2 +- .../music-library/albums/UpdateAlbum.http | 6 +- .../music-library/artists/AddArtist.http | 10 +- .../music-library/artists/DeleteArtist.http | 2 +- .../music-library/artists/GetArtist.http | 2 +- .../artists/GetArtistAlbums.http | 2 +- .../artists/GetArtistAlbumsLite.http | 2 +- .../music-library/artists/GetArtists.http | 2 +- .../music-library/artists/GetArtistsLite.http | 2 +- .../music-library/artists/UpdateArtist.http | 218 +- .../music-library/tracks/AddTrack.http | 6 +- .../music-library/tracks/DeleteTrack.http | 2 +- .../music-library/tracks/GetTrack.http | 2 +- .../music-library/tracks/UpdateTrack.http | 7 +- .../book-library/books/GetBook.http | 3 +- .../book-library/books/UpdateBookCover.http | 4 +- .../books/reading/GetReadingAvailability.http | 2 +- .../books/reading/GetReadingManifest.http | 2 +- .../books/reading/GetReadingResource.http | 2 +- .../books/reading/GetReadingSection.http | 2 +- .../Core/Mapping/CalibreMapper.cs | 39 +- .../Core/Mapping/OpenLibraryMapper.cs | 78 +- .../Core/OpenLibraryBookMetadataProvider.cs | 103 +- .../MusicLibrary/Albums/AlbumLiteRow.cs | 26 + .../MusicLibrary/Artists/ArtistLiteRow.cs | 21 + .../MusicLibrary/Tracks/TrackLiteRow.cs | 31 + .../MusicLibrary/AlbumContributorEntity.cs | 56 + .../AudioLibrary/MusicLibrary/AlbumEntity.cs | 207 ++ .../MusicLibrary/ArtistContributorEntity.cs | 56 + .../AudioLibrary/MusicLibrary/ArtistEntity.cs | 71 + .../MusicLibrary/AudioRatingEntity.cs | 22 + .../MusicLibrary/TrackContributorEntity.cs | 56 + .../AudioLibrary/MusicLibrary/TrackEntity.cs | 242 ++ .../MusicLibrary/TrackIsrcEntity.cs | 14 + .../MusicLibrary/TrackMoodEntity.cs | 14 + .../BookLibrary/BookEntity.cs | 4 +- .../{Books => BookLibrary}/IBookRepository.cs | 13 +- .../MusicLibrary/IAlbumRepository.cs | 41 + .../MusicLibrary/IArtistRepository.cs | 22 + .../MusicLibrary/ITrackRepository.cs | 41 + .../Albums/AddAlbumCommandMapping.cs | 108 + .../Albums/AddAlbumRequestMapping.cs | 51 + .../MusicLibrary/Albums/AlbumEntityMapping.cs | 240 ++ .../Albums/AlbumLiteRowMapping.cs | 56 + .../MusicLibrary/Albums/AlbumMapping.cs | 79 + .../Albums/AlbumMetadataDtoMapping.cs | 81 + .../Albums/DeleteAlbumRequestMapping.cs | 23 + .../Albums/GetAlbumRequestMapping.cs | 23 + .../GetAlbumTracksLiteRequestMapping.cs | 25 + .../Albums/GetAlbumTracksRequestMapping.cs | 23 + .../Albums/UpdateAlbumCommandMapping.cs | 96 + .../Albums/UpdateAlbumRequestMapping.cs | 37 + .../Artists/AddArtistCommandMapping.cs | 62 + .../Artists/AddArtistRequestMapping.cs | 31 + .../Artists/ArtistEntityMapping.cs | 119 + .../Artists/ArtistLiteRowMapping.cs | 55 + .../MusicLibrary/Artists/ArtistMapping.cs | 47 + .../GetArtistAlbumsLiteRequestMapping.cs | 25 + .../Artists/GetArtistAlbumsRequestMapping.cs | 23 + .../Artists/GetArtistRequestMapping.cs | 23 + .../Artists/GetArtistsLiteRequestMapping.cs | 26 + .../Artists/GetArtistsRequestMapping.cs | 26 + .../Artists/UpdateArtistCommandMapping.cs | 66 + .../Artists/UpdateArtistRequestMapping.cs | 33 + .../Common/AudioRatingDtoMapping.cs | 45 + .../Common/AudioRatingEntityMapping.cs | 71 + .../MusicLibrary/Common/AudioRatingMapping.cs | 39 + .../MusicLibrary/Common/IsrcDtoMapping.cs | 39 + .../MusicLibrary/Common/IsrcEntityMapping.cs | 62 + .../MusicLibrary/Common/IsrcMapping.cs | 36 + .../MusicLibrary/Common/MoodDtoMapping.cs | 39 + .../MusicLibrary/Common/MoodEntityMapping.cs | 62 + .../MusicLibrary/Common/MoodMapping.cs | 36 + .../Tracks/AddTrackCommandMapping.cs | 107 + .../Tracks/AddTrackRequestMapping.cs | 58 + .../Tracks/AudioMetadataDtoMapping.cs | 82 + .../Tracks/DeleteTrackRequestMapping.cs | 23 + .../Tracks/GetTrackRequestMapping.cs | 23 + .../MusicLibrary/Tracks/TrackEntityMapping.cs | 249 ++ .../Tracks/TrackLiteRowMapping.cs | 57 + .../MusicLibrary/Tracks/TrackMapping.cs | 82 + .../Tracks/UpdateTrackCommandMapping.cs | 100 + .../Tracks/UpdateTrackRequestMapping.cs | 44 + .../Books/AddBookCommandMapping.cs | 11 +- .../BookLibrary/Books/BookEntityMapping.cs | 8 +- .../BookLibrary/Books/BookMapping.cs | 2 +- .../GetReadingAvailabilityRequestMapping.cs | 24 - .../Books/GetReadingManifestRequestMapping.cs | 24 - .../Books/GetReadingResourceRequestMapping.cs | 25 - .../Books/GetReadingSectionRequestMapping.cs | 25 - .../Books/UpdateBookCoverCommandMapping.cs | 51 + .../WrittenContentMetadataDtoMapping.cs | 63 + .../Commands/AddAlbum/AddAlbumCommand.cs | 44 + .../AddAlbum/AddAlbumCommandHandler.cs | 193 ++ .../AddAlbum/AddAlbumCommandValidator.cs | 510 ++++ .../DeleteAlbum/DeleteAlbumCommand.cs | 16 + .../DeleteAlbum/DeleteAlbumCommandHandler.cs | 84 + .../DeleteAlbumCommandValidator.cs | 26 + .../UpdateAlbum/UpdateAlbumCommand.cs | 43 + .../UpdateAlbum/UpdateAlbumCommandHandler.cs | 171 ++ .../UpdateAlbumCommandValidator.cs | 278 ++ .../Albums/Queries/GetAlbum/GetAlbumQuery.cs | 16 + .../Queries/GetAlbum/GetAlbumQueryHandler.cs | 82 + .../GetAlbum/GetAlbumQueryValidator.cs | 26 + .../GetAlbumTracks/GetAlbumTracksQuery.cs | 16 + .../GetAlbumTracksQueryHandler.cs | 83 + .../GetAlbumTracksQueryValidator.cs | 26 + .../GetAlbumTracksLiteQuery.cs | 20 + .../GetAlbumTracksLiteQueryHandler.cs | 91 + .../GetAlbumTracksLiteQueryValidator.cs | 26 + .../Commands/AddArtist/AddArtistCommand.cs | 29 + .../AddArtist/AddArtistCommandHandler.cs | 189 ++ .../AddArtist/AddArtistCommandValidator.cs | 547 ++++ .../DeleteArtist/DeleteArtistCommand.cs | 17 + .../DeleteArtistCommandHandler.cs | 105 + .../DeleteArtistCommandValidator.cs | 40 + .../UpdateArtist/UpdateArtistCommand.cs | 31 + .../UpdateArtistCommandHandler.cs | 203 ++ .../UpdateArtistCommandValidator.cs | 557 ++++ .../Queries/GetArtist/GetArtistQuery.cs | 16 + .../GetArtist/GetArtistQueryHandler.cs | 82 + .../GetArtist/GetArtistQueryValidator.cs | 26 + .../GetArtistAlbums/GetArtistAlbumsQuery.cs | 16 + .../GetArtistAlbumsQueryHandler.cs | 83 + .../GetArtistAlbumsQueryValidator.cs | 26 + .../GetArtistAlbumsLiteQuery.cs | 20 + .../GetArtistAlbumsLiteQueryHandler.cs | 91 + .../GetArtistAlbumsLiteQueryValidator.cs | 26 + .../Queries/GetArtists/GetArtistsQuery.cs | 22 + .../GetArtists/GetArtistsQueryHandler.cs | 92 + .../GetArtists/GetArtistsQueryValidator.cs | 26 + .../GetArtistsLite/GetArtistsLiteQuery.cs | 22 + .../GetArtistsLiteQueryHandler.cs | 92 + .../GetArtistsLiteQueryValidator.cs | 26 + .../Commands/AddTrack/AddTrackCommand.cs | 56 + .../AddTrack/AddTrackCommandHandler.cs | 193 ++ .../AddTrack/AddTrackCommandValidator.cs | 284 ++ .../DeleteTrack/DeleteTrackCommand.cs | 16 + .../DeleteTrack/DeleteTrackCommandHandler.cs | 84 + .../DeleteTrackCommandValidator.cs | 26 + .../UpdateTrack/UpdateTrackCommand.cs | 55 + .../UpdateTrack/UpdateTrackCommandHandler.cs | 150 + .../UpdateTrackCommandValidator.cs | 275 ++ .../Tracks/Queries/GetTrack/GetTrackQuery.cs | 16 + .../Queries/GetTrack/GetTrackQueryHandler.cs | 82 + .../GetTrack/GetTrackQueryValidator.cs | 26 + .../Books/Commands/AddBook/AddBookCommand.cs | 4 +- .../Commands/AddBook/AddBookCommandHandler.cs | 2 +- .../AddBook/AddBookCommandValidator.cs | 8 +- .../Commands/UpdateBook/UpdateBookCommand.cs | 2 +- .../UpdateBook/UpdateBookCommandHandler.cs | 17 +- .../UpdateBook/UpdateBookCommandValidator.cs | 12 +- .../UpdateBookCover/UpdateBookCoverCommand.cs | 7 +- .../UpdateBookCoverCommandHandler.cs | 79 +- .../UpdateBookCoverCommandValidator.cs | 24 +- .../Queries/GetBooks/GetBooksQueryHandler.cs | 2 +- .../GetBooksLite/GetBooksLiteQueryHandler.cs | 2 +- .../GetBooksLiteQueryValidator.cs | 4 +- .../GetReadingAvailabilityQuery.cs | 7 +- .../GetReadingAvailabilityQueryHandler.cs | 13 +- .../GetReadingAvailabilityQueryValidator.cs | 18 +- .../GetReadingManifestQuery.cs | 7 +- .../GetReadingManifestQueryHandler.cs | 13 +- .../GetReadingManifestQueryValidator.cs | 18 +- .../GetReadingResourceQuery.cs | 11 +- .../GetReadingResourceQueryHandler.cs | 15 +- .../GetReadingResourceQueryValidator.cs | 19 +- .../GetReadingSectionQuery.cs | 11 +- .../GetReadingSectionQueryHandler.cs | 15 +- .../GetReadingSectionQueryValidator.cs | 19 +- ...tLibraryBookReaderEnabledCommandHandler.cs | 4 +- .../GetLibraryBookReadersQueryHandler.cs | 6 +- .../AudioLibrary/AudioRatingDto.cs | 22 + .../MusicLibrary/AlbumMetadataDto.cs | 40 + .../MusicLibrary/AudioMetadataDto.cs | 43 + .../AudioLibrary/MusicLibrary/IsrcDto.cs | 14 + .../MusicLibrary/Albums/AddAlbumRequest.cs | 40 + .../MusicLibrary/Albums/DeleteAlbumRequest.cs | 17 + .../MusicLibrary/Albums/GetAlbumRequest.cs | 17 + .../Albums/GetAlbumTracksLiteRequest.cs | 21 + .../Albums/GetAlbumTracksRequest.cs | 17 + .../MusicLibrary/Albums/UpdateAlbumRequest.cs | 37 + .../MusicLibrary/Artists/AddArtistRequest.cs | 26 + .../Artists/GetArtistAlbumsLiteRequest.cs | 19 + .../Artists/GetArtistAlbumsRequest.cs | 15 + .../MusicLibrary/Artists/GetArtistRequest.cs | 15 + .../Artists/GetArtistsLiteRequest.cs | 21 + .../MusicLibrary/Artists/GetArtistsRequest.cs | 21 + .../Artists/UpdateArtistRequest.cs | 26 + .../MusicLibrary/Tracks/AddTrackRequest.cs | 49 + .../MusicLibrary/Tracks/DeleteTrackRequest.cs | 19 + .../MusicLibrary/Tracks/GetTrackRequest.cs | 19 + .../MusicLibrary/Tracks/UpdateTrackRequest.cs | 49 + .../BookLibrary/Books/AddBookRequest.cs | 2 +- .../Reading/GetReadingAvailabilityRequest.cs | 15 - .../Reading/GetReadingManifestRequest.cs | 15 - .../Reading/GetReadingResourceRequest.cs | 17 - .../Books/Reading/GetReadingSectionRequest.cs | 17 - .../MusicLibrary/Albums/AlbumLiteResponse.cs | 19 + .../MusicLibrary/Albums/AlbumResponse.cs | 49 + .../Artists/ArtistLiteResponse.cs | 17 + .../MusicLibrary/Artists/ArtistResponse.cs | 34 + .../MusicLibrary/Tracks/TrackLiteResponse.cs | 21 + .../MusicLibrary/Tracks/TrackResponse.cs | 59 + .../Books/UpdateBookCoverResponse.cs | 14 + .../Configuration/AlbumConfiguration.cs | 183 ++ .../AlbumContributorConfiguration.cs | 57 + .../Configuration/ArtistConfiguration.cs | 58 + .../ArtistContributorConfiguration.cs | 57 + .../Common/Configuration/BookConfiguration.cs | 8 +- .../Configuration/TrackConfiguration.cs | 224 ++ .../TrackContributorConfiguration.cs | 57 + ...ryAndCanonicalContributorRoles.Designer.cs | 2606 +++++++++++++++++ ...usicLibraryAndCanonicalContributorRoles.cs | 680 +++++ .../{Books => BookLibrary}/BookRepository.cs | 75 +- .../BookAlphaFilterSpecification.cs | 2 +- .../Specifications/BookSearchSpecification.cs | 2 +- .../MusicLibrary/AlbumRepository.cs | 269 ++ .../MusicLibrary/ArtistRepository.cs | 362 +++ .../MusicLibrary/TrackRepository.cs | 247 ++ .../Common/Errors/Errors.MediaContributor.cs | 1 + .../MusicLibraryAggregate/Artist.cs | 100 +- .../MusicLibraryAggregate/Entities/Album.cs | 99 +- .../MusicLibraryAggregate/Entities/Track.cs | 103 +- .../ValueObjects/MusicBrainzId.cs | 3 + .../BookLibraryAggregate/Book.cs | 34 +- .../Services/BookLibraryService.cs | 17 - .../Services/IBookLibraryService.cs | 25 - .../ValueObjects/BookLibraryId.cs | 54 - .../Books/BooksFileSystemDiscoveryJob.cs | 8 +- .../BookLibrary/Artwork/BookArtworkService.cs | 6 +- .../MusicLibrary/ApiRoutes.Albums.cs | 23 + .../MusicLibrary/ApiRoutes.Artists.cs | 20 + .../MusicLibrary/ApiRoutes.Tracks.cs | 17 + .../BookLibrary/ApiRoutes.Books.cs | 20 +- .../Albums/AddAlbum/AddAlbumEndpoint.cs | 57 + .../AddAlbum/AddAlbumEndpointSummary.cs | 779 +++++ .../Albums/DeleteAlbum/DeleteAlbumEndpoint.cs | 53 + .../DeleteAlbum/DeleteAlbumEndpointSummary.cs | 110 + .../Albums/GetAlbum/GetAlbumEndpoint.cs | 55 + .../GetAlbum/GetAlbumEndpointSummary.cs | 228 ++ .../GetAlbumTracks/GetAlbumTracksEndpoint.cs | 56 + .../GetAlbumTracksEndpointSummary.cs | 335 +++ .../GetAlbumTracksLiteEndpoint.cs | 56 + .../GetAlbumTracksLiteEndpointSummary.cs | 144 + .../Albums/UpdateAlbum/UpdateAlbumEndpoint.cs | 58 + .../UpdateAlbum/UpdateAlbumEndpointSummary.cs | 388 +++ .../Artists/AddArtist/AddArtistEndpoint.cs | 56 + .../AddArtist/AddArtistEndpointSummary.cs | 917 ++++++ .../DeleteArtist/DeleteArtistEndpoint.cs | 54 + .../DeleteArtistEndpointSummary.cs | 114 + .../Artists/GetArtist/GetArtistEndpoint.cs | 55 + .../GetArtist/GetArtistEndpointSummary.cs | 136 + .../GetArtistAlbumsEndpoint.cs | 56 + .../GetArtistAlbumsEndpointSummary.cs | 302 ++ .../GetArtistAlbumsLiteEndpoint.cs | 56 + .../GetArtistAlbumsLiteEndpointSummary.cs | 139 + .../Artists/GetArtists/GetArtistsEndpoint.cs | 56 + .../GetArtists/GetArtistsEndpointSummary.cs | 147 + .../GetArtistsLite/GetArtistsLiteEndpoint.cs | 56 + .../GetArtistsLiteEndpointSummary.cs | 126 + .../UpdateArtist/UpdateArtistEndpoint.cs | 57 + .../UpdateArtistEndpointSummary.cs | 903 ++++++ .../Tracks/AddTrack/AddTrackEndpoint.cs | 58 + .../AddTrack/AddTrackEndpointSummary.cs | 457 +++ .../Tracks/DeleteTrack/DeleteTrackEndpoint.cs | 53 + .../DeleteTrack/DeleteTrackEndpointSummary.cs | 112 + .../Tracks/GetTrack/GetTrackEndpoint.cs | 55 + .../GetTrack/GetTrackEndpointSummary.cs | 249 ++ .../Tracks/UpdateTrack/UpdateTrackEndpoint.cs | 59 + .../UpdateTrack/UpdateTrackEndpointSummary.cs | 386 +++ .../Books/AddBook/AddBookEndpoint.cs | 2 +- .../Books/AddBook/AddBookEndpointSummary.cs | 49 +- .../GetReadingAvailabilityEndpoint.cs | 21 +- .../GetReadingAvailabilityEndpointSummary.cs | 75 +- .../GetReadingManifestEndpoint.cs | 21 +- .../GetReadingManifestEndpointSummary.cs | 108 +- .../GetReadingResourceEndpoint.cs | 22 +- .../GetReadingResourceEndpointSummary.cs | 115 +- .../GetReadingSectionEndpoint.cs | 22 +- .../GetReadingSectionEndpointSummary.cs | 113 +- .../Books/UpdateBook/UpdateBookEndpoint.cs | 2 +- .../UpdateBook/UpdateBookEndpointSummary.cs | 19 +- .../UpdateBookCoverEndpoint.cs | 25 +- .../UpdateBookCoverEndpointSummary.cs | 71 +- .../BookLibrary/BookDto.cs | 2 +- .../BookLibrary/UpdateBookCoverDto.cs | 17 + .../BookLibrary/Books/GetBookRequest.cs | 9 +- .../GetBookReadingAvailabilityRequest.cs | 4 +- .../Reading/GetBookReadingManifestRequest.cs | 4 +- .../Reading/GetBookReadingResourceRequest.cs | 4 +- .../Reading/GetBookReadingSectionRequest.cs | 4 +- .../Books/Reading/ReadBookViewRequest.cs | 4 +- .../Common/Routes/ApiRoutes.Books.cs | 16 +- .../Common/Routes/WebRoutes.Books.cs | 8 +- .../Books/EditBook/EditBookViewEndpoint.cs | 10 +- .../EditBook/EditBookViewEndpointSummary.cs | 6 +- .../GetBookDetails/GetBookDetailsEndpoint.cs | 6 +- .../GetBookDetailsEndpointSummary.cs | 6 +- .../GetLibraryItemsEndpoint.cs | 21 +- .../Books/Index/BooksIndexViewEndpoint.cs | 2 +- .../GetReadingAvailabilityEndpoint.cs | 2 +- .../GetReadingAvailabilityEndpointSummary.cs | 4 +- .../GetReadingManifestEndpoint.cs | 2 +- .../GetReadingManifestEndpointSummary.cs | 4 +- .../GetReadingResourceEndpoint.cs | 1 + .../GetReadingResourceEndpointSummary.cs | 4 +- .../GetReadingSectionEndpoint.cs | 1 + .../GetReadingSectionEndpointSummary.cs | 4 +- .../Reading/Read/ReadViewEndpointSummary.cs | 4 +- .../UpdateBookCoverEndpoint.cs | 44 +- .../BookLibrary/Books/Item.ar-SA.resx | 86 +- .../BookLibrary/Books/Item.de-DE.resx | 86 +- .../BookLibrary/Books/Item.en-US.resx | 86 +- .../BookLibrary/Books/Item.es-ES.resx | 86 +- .../BookLibrary/Books/Item.fr-FR.resx | 86 +- .../BookLibrary/Books/Item.it-IT.resx | 86 +- .../BookLibrary/Books/Item.ja-JP.resx | 86 +- .../BookLibrary/Books/Item.resx | 86 +- .../BookLibrary/Books/Item.ro-RO.resx | 86 +- .../BookLibrary/Books/Item.uk-UA.resx | 86 +- .../BookLibrary/Books/Item.zh-CN.resx | 86 +- .../BookLibrary/Books/Index.cshtml | 10 +- .../BookLibrary/Books/Item.cshtml | 81 +- .../BookLibrary/Books/Read.cshtml | 9 +- .../UpdateBookCoverCommandFixture.cs | 7 +- .../GetReadingAvailabilityQueryFixture.cs | 6 +- .../GetReadingManifestQueryFixture.cs | 6 +- .../GetReadingResourceQueryFixture.cs | 6 +- .../GetReadingSectionQueryFixture.cs | 6 +- .../GetReadingAvailabilityRequestFixture.cs | 37 - .../GetReadingManifestRequestFixture.cs | 37 - .../GetReadingResourceRequestFixture.cs | 39 - .../GetReadingSectionRequestFixture.cs | 39 - .../Books/UpdateBookCoverResponseFixture.cs | 40 + .../ValueObjects/BookLibraryIdFixture.cs | 37 - .../BookLibrary/UpdateBookCoverDtoFixture.cs | 41 + .../Books/GetBookRequestFixture.cs | 6 +- ...etBookReadingAvailabilityRequestFixture.cs | 6 +- .../GetBookReadingManifestRequestFixture.cs | 6 +- .../GetBookReadingResourceRequestFixture.cs | 6 +- .../GetBookReadingSectionRequestFixture.cs | 6 +- .../Reading/ReadBookViewRequestFixture.cs | 6 +- .../BookRepositoryTests.cs | 16 +- .../Books/BooksFileSystemDiscoveryJobTests.cs | 13 +- .../Reading/BookReadingServiceTests.cs | 1 + .../Common/Converters/BookJsonConverter.cs | 286 -- .../Books/AddBook/AddBookEndpointTests.cs | 145 +- .../GetReadingAvailabilityEndpointTests.cs | 73 +- .../GetReadingManifestEndpointTests.cs | 56 +- .../GetReadingResourceEndpointTests.cs | 56 +- .../GetReadingSectionEndpointTests.cs | 56 +- .../UpdateBook/UpdateBookEndpointTests.cs | 41 +- .../UpdateBookCoverEndpointTests.cs | 123 +- .../EditBook/EditBookViewEndpointTests.cs | 4 +- .../GetBookDetailsEndpointTests.cs | 11 +- .../GetLibraryItemsEndpointTests.cs | 2 +- .../GetReadingAvailabilityEndpointTests.cs | 12 +- .../GetReadingManifestEndpointTests.cs | 10 +- .../GetReadingSectionEndpointTests.cs | 5 +- .../UpdateBookCoverEndpointTests.cs | 52 +- .../Books/AddBook/AddBookEndpointTests.cs | 2 +- .../GetReadingAvailabilityEndpointTests.cs | 64 +- .../GetReadingManifestEndpointTests.cs | 60 +- .../GetReadingResourceEndpointTests.cs | 68 +- .../GetReadingSectionEndpointTests.cs | 68 +- .../UpdateBook/UpdateBookEndpointTests.cs | 2 +- .../UpdateBookCoverEndpointTests.cs | 58 +- .../GetBookDetailsEndpointTests.cs | 9 +- .../GetLibraryItemsEndpointTests.cs | 4 +- .../UpdateBookCoverEndpointTests.cs | 20 +- .../BookLibrary/Books/BookMappingTests.cs | 5 +- ...tReadingAvailabilityRequestMappingTests.cs | 32 - .../GetReadingManifestRequestMappingTests.cs | 32 - .../GetReadingResourceRequestMappingTests.cs | 33 - .../GetReadingSectionRequestMappingTests.cs | 33 - .../UpdateBookCoverCommandMappingTests.cs | 68 + .../WrittenContentMetadataDtoMappingTests.cs | 119 + .../AddBook/AddBookCommandHandlerTests.cs | 18 +- .../AddBook/AddBookCommandValidatorTests.cs | 4 +- .../UpdateBookCommandHandlerTests.cs | 91 +- .../UpdateBookCommandValidatorTests.cs | 4 +- .../UpdateBookCoverCommandHandlerTests.cs | 203 +- .../UpdateBookCoverCommandValidatorTests.cs | 93 +- .../GetBook/GetBookQueryHandlerTests.cs | 4 +- .../GetBooks/GetBooksQueryHandlerTests.cs | 2 +- .../GetBooksLiteQueryHandlerTests.cs | 2 +- ...GetReadingAvailabilityQueryHandlerTests.cs | 82 +- ...tReadingAvailabilityQueryValidatorTests.cs | 53 +- .../GetReadingManifestQueryHandlerTests.cs | 82 +- .../GetReadingManifestQueryValidatorTests.cs | 53 +- .../GetReadingResourceQueryHandlerTests.cs | 76 +- .../GetReadingResourceQueryValidatorTests.cs | 79 +- .../GetReadingSectionQueryHandlerTests.cs | 92 +- .../GetReadingSectionQueryValidatorTests.cs | 79 +- ...aryBookReaderEnabledCommandHandlerTests.cs | 1 + .../GetLibraryBookReadersQueryHandlerTests.cs | 20 +- .../BookLibrary/BookMetadataDtoTests.cs | 2 +- .../GetReadingAvailabilityRequestTests.cs | 49 - .../Reading/GetReadingManifestRequestTests.cs | 49 - .../Reading/GetReadingResourceRequestTests.cs | 50 - .../Reading/GetReadingSectionRequestTests.cs | 50 - .../Books/UpdateBookCoverResponseTests.cs | 49 + .../BookRepositoryTests.cs | 67 +- .../BookAlphaFilterSpecificationTests.cs | 190 ++ .../BookSearchSpecificationTests.cs | 4 +- .../BookLibraryAggregate/BookTests.cs | 64 +- .../Services/BookLibraryServiceTests.cs | 24 - .../ValueObjects/BookLibraryIdTests.cs | 72 - .../Books/BooksFileSystemDiscoveryJobTests.cs | 5 +- .../Reading/BookReadingServiceTests.cs | 1 + .../Core/Mapping/CalibreMapperTests.cs | 18 +- .../Core/Mapping/OpenLibraryMapperTests.cs | 126 +- .../OpenLibraryBookMetadataProviderTests.cs | 16 +- .../Books/AddBook/AddBookEndpointTests.cs | 33 +- .../GetReadingAvailabilityEndpointTests.cs | 122 +- .../GetReadingManifestEndpointTests.cs | 109 +- .../GetReadingResourceEndpointTests.cs | 130 +- .../GetReadingSectionEndpointTests.cs | 126 +- .../UpdateBook/UpdateBookEndpointTests.cs | 47 +- .../UpdateBookCoverEndpointTests.cs | 145 +- .../GetLibraryBookReadersEndpointTests.cs | 2 +- ...etLibraryBookReaderEnabledEndpointTests.cs | 2 +- .../GetBookDetailsEndpointTests.cs | 6 +- .../GetLibraryItemsEndpointTests.cs | 7 +- .../GetReadingAvailabilityEndpointTests.cs | 10 +- .../GetReadingManifestEndpointTests.cs | 6 +- .../GetReadingResourceEndpointTests.cs | 1 + .../GetReadingSectionEndpointTests.cs | 1 + .../UpdateBookCoverEndpointTests.cs | 79 +- 439 files changed, 28235 insertions(+), 3156 deletions(-) create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumContributorEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AlbumEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistContributorEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/ArtistEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/AudioRatingEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackContributorEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackIsrcEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackMoodEntity.cs rename src/Lumina.Application/Common/DataAccess/Repositories/{Books => BookLibrary}/IBookRepository.cs (94%) create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IArtistRepository.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMetadataDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeleteAlbumRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/AudioRatingMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/IsrcMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Common/MoodMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AudioMetadataDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeleteTrackRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMapping.cs delete mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/DeleteArtist/DeleteArtistCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQuery.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandler.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidator.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/AudioRatingDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AlbumMetadataDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/AudioMetadataDto.cs create mode 100644 src/Lumina.Contracts/DTO/MediaLibrary/AudioLibrary/MusicLibrary/IsrcDto.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeleteAlbumRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeleteTrackRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequest.cs create mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequest.cs delete mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequest.cs delete mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequest.cs delete mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequest.cs delete mode 100644 src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequest.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackResponse.cs create mode 100644 src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/AlbumConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/AlbumContributorConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/ArtistConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/ArtistContributorConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/TrackContributorConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260910173956_AddsMusicLibraryAndCanonicalContributorRoles.cs rename src/Lumina.DataAccess/Core/Repositories/{Books => BookLibrary}/BookRepository.cs (91%) rename src/Lumina.DataAccess/Core/Repositories/{Books => BookLibrary}/Specifications/BookAlphaFilterSpecification.cs (99%) rename src/Lumina.DataAccess/Core/Repositories/{Books => BookLibrary}/Specifications/BookSearchSpecification.cs (95%) create mode 100644 src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs delete mode 100644 src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryService.cs delete mode 100644 src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/IBookLibraryService.cs delete mode 100644 src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryId.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Artists.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/DeleteArtist/DeleteArtistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDto.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestFixture.cs delete mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseFixture.cs delete mode 100644 tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/UpdateBookCoverDtoFixture.cs rename tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/{Books => BookLibrary}/BookRepositoryTests.cs (91%) delete mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Converters/BookJsonConverter.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingAvailabilityRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingManifestRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingResourceRequestMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetReadingSectionRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverCommandMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMappingTests.cs delete mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailabilityRequestTests.cs delete mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifestRequestTests.cs delete mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingResourceRequestTests.cs delete mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingSectionRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseTests.cs rename tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/{Books => BookLibrary}/BookRepositoryTests.cs (95%) create mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/Specifications/BookAlphaFilterSpecificationTests.cs rename tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/{Books => BookLibrary}/Specifications/BookSearchSpecificationTests.cs (96%) delete mode 100644 tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs delete mode 100644 tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs diff --git a/docs/technical/api/library/audio-library/music-library/Api.Albums.md b/docs/technical/api/library/audio-library/music-library/Api.Albums.md index 5fc35982..8d95e6ef 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Albums.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Albums.md @@ -2,15 +2,15 @@ - [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) - - [Add Album](#add-album) - - [Add Album Request](#add-album-request) - - [Add Album Response](#add-album-response) - [Get Album](#get-album) - [Get Album Request](#get-album-request) - [Get Album Response](#get-album-response) @@ -21,135 +21,16 @@ ## Album -### Get Artist Albums - -#### Get Artist Albums Request - -```js -GET api/v1/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", - "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, - "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, - "ratings": [ - { - "value": 4.5, - "maxValue": 5, - "source": "MusicBrainz", - "voteCount": 2345 - }, - { - "value": 4.8, - "maxValue": 5, - "source": "LastFm", - "voteCount": 1234 - } - ], - "originalReleaseDate": "1975-11-21", - "originalReleaseYear": 1975, - "reReleaseDate": null, - "reReleaseYear": null, - "releaseCountry": "GB", - "releaseVersion": "Remastered", - "languageCode": "en", - "languageName": "English", - "languageNativeName": "English", - "originalLanguageCode": "en", - "originalLanguageName": "English", - "originalLanguageNativeName": "English", - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], - "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" - } - ] - } -] -``` - - -### Get Artist Albums Lite - -#### Get Artist Albums Lite Request - -```js -GET api/v1/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 -} -``` - - ### Add Album #### Add Album Request ```js -POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums ``` ```json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "metadata": { "title": "A Night at the Opera", "originalTitle": "A Night at the Opera", @@ -191,7 +72,7 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", - "credits": [ + "contributors": [ { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } ], @@ -211,8 +92,6 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums ], "tracks": [ { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -260,7 +139,7 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -287,22 +166,20 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums ] }, { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", - "path": "/music/queen/a-night-at-the-opera/02-youre-my-best-friend.flac", + "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. It was written by John Deacon and originally released on the album A Night at the Opera in 1975.", - "durationInSeconds": 157, + "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": 895, + "bitrate": 912, "releaseInfo": { - "originalReleaseDate": "1975-06-18", - "originalReleaseYear": 1975, + "originalReleaseDate": "1976-06-18", + "originalReleaseYear": 1976, "reReleaseDate": null, "reReleaseYear": null, "releaseCountry": "GB", @@ -320,23 +197,23 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums }, "genres": [ { "name": "Rock" }, - { "name": "Pop" } + { "name": "Pop Rock" } ], "tags": [ { "name": "classic" }, - { "name": "pop" } + { "name": "love" } ] }, - "trackNumber": 2, + "trackNumber": 7, "discNumber": 1, "script": "Latn", - "key": "CMajor", - "bpm": 128, + "key": "BMajor", + "bpm": 118, "work": "You're My Best Friend", - "musicBrainzRecordingId": "a0b1c2d3-e4f5-4a6b-8c7d-9e0f1a2b3c4d", - "musicBrainzTrackId": "b1c2d3e4-f5a6-4b7c-9d0e-1f2a3b4c5d6e", - "musicBrainzWorkId": "c2d3e4f5-a6b7-4c8d-9e0f-1a2b3c4d5e6f", - "credits": [ + "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" } ], @@ -345,21 +222,21 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums "value": 4.2, "maxValue": 5, "source": "MusicBrainz", - "voteCount": 1890 + "voteCount": 1234 }, { - "value": 4.1, + "value": 4.4, "maxValue": 5, "source": "LastFm", - "voteCount": 987 + "voteCount": 567 } ], "moods": [ - { "name": "upbeat" }, - { "name": "happy" } + { "name": "happy" }, + { "name": "warm" } ], "isrcs": [ - { "value": "GBUM71029605" } + { "value": "GBUM71029609" } ] } ] @@ -372,35 +249,54 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums 201 Created ``` -The response carries the full details of the newly created album, using the same shape as the [Get Album Response](#get-album-response). - - -### Get Album - -#### Get Album Request - -```js -GET api/v1/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", - "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, + "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", @@ -409,6 +305,16 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "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, @@ -423,50 +329,428 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "voteCount": 1234 } ], - "originalReleaseDate": "1975-11-21", - "originalReleaseYear": 1975, - "reReleaseDate": null, - "reReleaseYear": null, - "releaseCountry": "GB", - "releaseVersion": "Remastered", - "languageCode": "en", - "languageName": "English", - "languageNativeName": "English", - "originalLanguageCode": "en", - "originalLanguageName": "English", - "originalLanguageNativeName": "English", - "genres": [ + "tracks": [ { - "name": "Rock" + "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" } + ] }, { - "name": "Progressive Rock" - } - ], - "tags": [ - { - "name": "classic" - }, - { - "name": "vinyl" + "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/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f ``` ```json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "metadata": { "title": "A Night at the Opera", "originalTitle": "A Night at the Opera", @@ -508,7 +792,7 @@ PUT api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", - "credits": [ + "contributors": [ { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } ], @@ -541,7 +825,7 @@ The response carries the full details of the updated album, using the same shape ### Delete Album ```js -DELETE api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f ``` ```js diff --git a/docs/technical/api/library/audio-library/music-library/Api.Artists.md b/docs/technical/api/library/audio-library/music-library/Api.Artists.md index 7da65d84..33294047 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Artists.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Artists.md @@ -26,7 +26,7 @@ #### Add Artist Request ```js -POST api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists ``` ```json @@ -34,7 +34,7 @@ POST api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "name": "Queen", "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -81,7 +81,7 @@ POST api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", - "credits": [ + "contributors": [ { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } ], @@ -155,7 +155,7 @@ POST api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "isrcs": [ { "value": "GBUM71029604" } ], - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -229,7 +229,7 @@ POST api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "isrcs": [ { "value": "GBUM71029609" } ], - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } ], @@ -267,23 +267,238 @@ POST api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists "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, + "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" } + ] + } + ] + } + ], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } ``` - + ### Get Artists #### Get Artists Request ```js -GET api/v1/artists?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=queen +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists?currentPage=1&perPage=10&searchTerm=queen ``` | Query Parameter | Type | Description | | --- | --- | --- | -| `libraryId` | `string` (GUID) | Required. The Id of the media library whose artists are retrieved. | | `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. | @@ -303,6 +518,8 @@ GET api/v1/artists?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1& "name": "Queen", "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", + "contributors": [], + "albums": [], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": null } @@ -320,12 +537,11 @@ GET api/v1/artists?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1& #### Get Artists Lite Request ```js -GET api/v1/artists/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=queen +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/lite?currentPage=1&perPage=10&searchTerm=queen ``` | Query Parameter | Type | Description | | --- | --- | --- | -| `libraryId` | `string` (GUID) | Required. The Id of the media library whose artists are retrieved. | | `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. | @@ -357,7 +573,7 @@ GET api/v1/artists/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPa #### Get Artist Request ```js -GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ``` #### Get Artist Response @@ -373,6 +589,11 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a "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 } @@ -384,18 +605,230 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a #### Update Artist Request ```js -PUT api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a +PUT api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ``` ```json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "name": "Queen", "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", - "credits": [ + "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 + } + ] + } + ] + } ] } ``` @@ -413,6 +846,222 @@ PUT api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a "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, + "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" } + ] + } + ] + } + ], "createdOnUtc": "2025-01-01T12:00:00.0000000Z", "updatedOnUtc": "2025-02-01T12:00:00.0000000Z" } @@ -422,7 +1071,7 @@ PUT api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a ### Delete Artist ```js -DELETE api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a +DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{artistId} ``` ```js diff --git a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index 95a19180..9deedf51 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -26,7 +26,7 @@ #### Get Album Tracks Request ```js -GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +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 @@ -42,9 +42,22 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", - "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.", + "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", @@ -56,6 +69,16 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "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, @@ -70,40 +93,6 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "voteCount": 1234 } ], - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, - "originalReleaseDate": "1975-10-31", - "originalReleaseYear": 1975, - "reReleaseDate": null, - "reReleaseYear": null, - "releaseCountry": "GB", - "releaseVersion": "Original", - "languageCode": "en", - "languageName": "English", - "languageNativeName": "English", - "originalLanguageCode": "en", - "originalLanguageName": "English", - "originalLanguageNativeName": "English", - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], - "tags": [ - { - "name": "classic" - }, - { - "name": "epic" - } - ], "moods": [ { "name": "dramatic" @@ -127,7 +116,7 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 #### Get Album Tracks Lite Request ```js -GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/lite?currentPage=1&perPage=10 +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 | @@ -164,13 +153,11 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 #### Add Track Request ```js -POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks ``` ```json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -218,7 +205,7 @@ POST api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -260,7 +247,7 @@ The response carries the full details of the newly created track, using the same #### Get Track Request ```js -GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +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 @@ -275,9 +262,22 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", - "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.", + "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", @@ -289,6 +289,16 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "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, @@ -303,40 +313,6 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "voteCount": 1234 } ], - "durationInSeconds": 354, - "sampleRate": 44100, - "channels": 2, - "bitDepth": 16, - "audioCodec": "FLAC", - "bitrate": 980, - "originalReleaseDate": "1975-10-31", - "originalReleaseYear": 1975, - "reReleaseDate": null, - "reReleaseYear": null, - "releaseCountry": "GB", - "releaseVersion": "Original", - "languageCode": "en", - "languageName": "English", - "languageNativeName": "English", - "originalLanguageCode": "en", - "originalLanguageName": "English", - "originalLanguageNativeName": "English", - "genres": [ - { - "name": "Rock" - }, - { - "name": "Progressive Rock" - } - ], - "tags": [ - { - "name": "classic" - }, - { - "name": "epic" - } - ], "moods": [ { "name": "dramatic" @@ -359,14 +335,11 @@ GET api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 #### Update Track Request ```js -PUT api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +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 { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", - "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -414,7 +387,7 @@ PUT api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2 "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -454,7 +427,7 @@ The response carries the full details of the updated track, using the same shape ### Delete Track ```js -DELETE api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +DELETE 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 ``` ```js diff --git a/docs/technical/domain/Aggregates.AudioLibrary.md b/docs/technical/domain/Aggregates.AudioLibrary.md index f05b5821..08a4c673 100644 --- a/docs/technical/domain/Aggregates.AudioLibrary.md +++ b/docs/technical/domain/Aggregates.AudioLibrary.md @@ -8,7 +8,7 @@ ## [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 credits of the media contributors that make up an artist, or that performed on an album or a track, are carried as `MusicMediaContributorCredit` value objects. +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) @@ -20,7 +20,7 @@ class Artist string name, Optional website, Optional musicBrainzArtistId, - List credits, + List contributors, List albums); } ``` @@ -38,7 +38,7 @@ class Artist "musicBrainzArtistId": { "value": "00000000-0000-0000-0000-000000000000" }, - "credits": [], + "contributors": [], "albums": [ { "value": "00000000-0000-0000-0000-000000000000" @@ -60,7 +60,7 @@ class Album Optional musicBrainzReleaseId, Optional musicBrainzReleaseGroupId, Optional musicBrainzReleaseArtistId, - List credits, + List contributors, List ratings, List tracks); } @@ -120,7 +120,7 @@ class Album "musicBrainzReleaseArtistId": { "value": "00000000-0000-0000-0000-000000000000" }, - "credits": [], + "contributors": [], "ratings": [ { "value": 4.5, @@ -163,7 +163,7 @@ class Track Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, + List contributors, List ratings); } ``` @@ -238,7 +238,7 @@ class Track "musicBrainzWorkId": { "value": "00000000-0000-0000-0000-000000000000" }, - "credits": [], + "contributors": [], "ratings": [ { "value": 4.5, diff --git a/docs/technical/domain/Aggregates.WrittenContentLibrary.md b/docs/technical/domain/Aggregates.WrittenContentLibrary.md index fc113f94..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": [ diff --git a/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http b/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http index df67d1fd..1f173f5b 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/AddAlbum.http @@ -1,9 +1,8 @@ -POST {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums +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 { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "metadata": { "title": "A Night at the Opera", "originalTitle": "A Night at the Opera", @@ -45,7 +44,7 @@ Content-Type: application/json "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", - "credits": [ + "contributors": [ { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } ], @@ -65,8 +64,6 @@ Content-Type: application/json ], "tracks": [ { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -114,7 +111,7 @@ Content-Type: application/json "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -141,8 +138,6 @@ Content-Type: application/json ] }, { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "path": "/music/queen/a-night-at-the-opera/07-youre-my-best-friend.flac", "metadata": { "title": "You're My Best Friend", @@ -190,7 +185,7 @@ Content-Type: application/json "musicBrainzRecordingId": "0f3e4d5c-6b7a-4f8e-9d0c-1b2a3c4d5e6f", "musicBrainzTrackId": "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzWorkId": "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } ], 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 index ea05bc19..476d72c9 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/DeleteAlbum.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/DeleteAlbum.http @@ -1,2 +1,2 @@ -DELETE {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f 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 index 6d3d9d2b..5eceaf23 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/GetAlbum.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbum.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f 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 index ed7f3589..515d9753 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracks.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracks.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +GET {{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}} 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 index 9608438e..f61e8a86 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracksLite.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/GetAlbumTracksLite.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/lite?currentPage=1&perPage=10 +GET {{host}}/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 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 index 64b5f402..24d0c149 100644 --- a/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http +++ b/docs/technical/requests/library/audio-library/music-library/albums/UpdateAlbum.http @@ -1,10 +1,8 @@ -PUT {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "metadata": { "title": "A Night at the Opera", "originalTitle": "A Night at the Opera", @@ -46,7 +44,7 @@ Content-Type: application/json "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", - "credits": [ + "contributors": [ { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } ], diff --git a/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http b/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http index 1446968b..56cba33b 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/AddArtist.http @@ -1,4 +1,4 @@ -POST {{host}}/api/v1/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists +POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json @@ -6,7 +6,7 @@ Content-Type: application/json "name": "Queen", "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -53,7 +53,7 @@ Content-Type: application/json "musicBrainzReleaseId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", "musicBrainzReleaseGroupId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e", "musicBrainzReleaseArtistId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f", - "credits": [ + "contributors": [ { "contributorId": "0e7b4a6c-5f8d-6b9e-ca0b-3c4d5e6f7a8b", "role": "Producer" }, { "contributorId": "1a8c5b7d-6a9e-7c0f-db1c-4d5e6f7a8b9c", "role": "Engineer" } ], @@ -127,7 +127,7 @@ Content-Type: application/json "isrcs": [ { "value": "GBUM71029604" } ], - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], @@ -201,7 +201,7 @@ Content-Type: application/json "isrcs": [ { "value": "GBUM71029609" } ], - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "8c5f2e4a-3d6b-4f7c-ae8f-1a2b3c4d5e6f", "role": "BassGuitar" } ], 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 index 44e7fd83..47c6f62d 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/DeleteArtist.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/DeleteArtist.http @@ -1,2 +1,2 @@ -DELETE {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a +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 index c6d07206..2a56cc5d 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/GetArtist.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtist.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a +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 index 17702963..1d887e85 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbums.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbums.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums +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 index 3664a1f1..31325b3e 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbumsLite.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistAlbumsLite.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/lite?currentPage=1&perPage=10 +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 index 2ee9952a..0b41f86b 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/GetArtists.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtists.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=queen +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 index 69d7acda..c95805e1 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/GetArtistsLite.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/GetArtistsLite.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/lite?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a¤tPage=1&perPage=10&searchTerm=queen +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 index 297f3018..b0305b98 100644 --- a/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http +++ b/docs/technical/requests/library/audio-library/music-library/artists/UpdateArtist.http @@ -1,14 +1,226 @@ -PUT {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a +PUT {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/{{$guid}} Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", "name": "Queen", "website": "https://www.queenonline.com", "musicBrainzArtistId": "6f9c0b2a-1d3e-4a5b-8c7d-9e0f1a2b3c4d", - "credits": [ + "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/tracks/AddTrack.http b/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http index 0f9635d4..f9451ec8 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/AddTrack.http @@ -1,10 +1,8 @@ -POST {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks +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 { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -52,7 +50,7 @@ Content-Type: application/json "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], 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 index dde2601b..fdf81353 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/DeleteTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/DeleteTrack.http @@ -1,2 +1,2 @@ -DELETE {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +DELETE {{host}}/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 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 index fc356546..7842dd76 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/GetTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/GetTrack.http @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +GET {{host}}/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 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 index 3d6c6380..a792bfd1 100644 --- a/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http +++ b/docs/technical/requests/library/audio-library/music-library/tracks/UpdateTrack.http @@ -1,11 +1,8 @@ -PUT {{host}}/api/v1/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f +PUT {{host}}/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 Authorization: Bearer {{ACCESS_TOKEN}} Content-Type: application/json { - "artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a", - "albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f", - "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", "path": "/music/queen/a-night-at-the-opera/01-bohemian-rhapsody.flac", "metadata": { "title": "Bohemian Rhapsody", @@ -53,7 +50,7 @@ Content-Type: application/json "musicBrainzRecordingId": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a", "musicBrainzTrackId": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b", "musicBrainzWorkId": "f6a7b8c9-d0e1-4f2a-3b4c-5d6e7f8a9b0c", - "credits": [ + "contributors": [ { "contributorId": "6a3f0c2d-1b4e-4f5a-8c6d-9e0f1a2b3c4d", "role": "Vocals" }, { "contributorId": "7b4e1d3f-2c5a-4e6b-9d7e-0f1a2b3c4d5e", "role": "Guitar" } ], 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 index b2c5f4e7..4f88eaa8 100644 --- 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 @@ -1 +1,2 @@ -GET {{host}}/api/v1/books/{{$guid}} +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/UpdateBookCover.http b/docs/technical/requests/library/written-content-library/book-library/books/UpdateBookCover.http index e166556a..3762accb 100644 --- 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 @@ -1,9 +1,9 @@ -PUT {{host}}/api/v1/books/{{$guid}}/cover +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="file"; filename="cover.jpg" +Content-Disposition: form-data; name="cover"; filename="cover.jpg" Content-Type: image/jpeg < ./cover.jpg 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 index e5dcdb0e..60325776 100644 --- 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 @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/availability +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 index c5d92cab..7a8ad10a 100644 --- 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 @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/manifest +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 index 8133bb5b..c48a27b7 100644 --- 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 @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/resources/0f4d6e2b1c9a4f3e8d7c6b5a4f3e2d1c +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 index 1b382784..381cede6 100644 --- 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 @@ -1,2 +1,2 @@ -GET {{host}}/api/v1/books/{{$guid}}/reading/sections/chapter1 +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}/reading/sections/chapter1 Authorization: Bearer {{ACCESS_TOKEN}} 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/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..1fb5fd5a --- /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 ratings for this track. + /// + public List Ratings { 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 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 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/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs index 9f5ff93a..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 @@ -199,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 94% rename from src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs rename to src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs index f324e888..64ddf7cd 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Books/IBookRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/BookLibrary/IBookRepository.cs @@ -10,7 +10,7 @@ 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. @@ -20,7 +20,8 @@ public interface IBookRepository : IRepository, IUpdateRepositoryAction, IGetByIdRepositoryAction, IGetAllRepositoryAction, - IGetAllLiteRepositoryAction + IGetAllLiteRepositoryAction, + IDeleteByIdRepositoryAction { /// /// Gets all the books of the media library identified by . @@ -113,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/MusicLibrary/IAlbumRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IAlbumRepository.cs new file mode 100644 index 00000000..6928b9db --- /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, + IGetByIdRepositoryAction, + IDeleteByIdRepositoryAction +{ + /// + /// 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..b7143385 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.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.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, + IGetByIdRepositoryAction, + IDeleteByIdRepositoryAction +{ + /// + /// 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/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..6debf952 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AddAlbumCommandMapping.cs @@ -0,0 +1,108 @@ +#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) + { + Result musicBrainzReleaseIdResult = MusicBrainzId.Create(command.MusicBrainzReleaseId.Value); + if (musicBrainzReleaseIdResult.IsFailure) + return musicBrainzReleaseIdResult.Errors; + musicBrainzReleaseId = musicBrainzReleaseIdResult.Value; + } + Optional musicBrainzReleaseGroupId = Optional.None(); + if (command.MusicBrainzReleaseGroupId is not null) + { + Result musicBrainzReleaseGroupIdResult = MusicBrainzId.Create(command.MusicBrainzReleaseGroupId.Value); + if (musicBrainzReleaseGroupIdResult.IsFailure) + return musicBrainzReleaseGroupIdResult.Errors; + musicBrainzReleaseGroupId = musicBrainzReleaseGroupIdResult.Value; + } + Optional musicBrainzReleaseArtistId = Optional.None(); + if (command.MusicBrainzReleaseArtistId is not null) + { + Result musicBrainzReleaseArtistIdResult = MusicBrainzId.Create(command.MusicBrainzReleaseArtistId.Value); + if (musicBrainzReleaseArtistIdResult.IsFailure) + return musicBrainzReleaseArtistIdResult.Errors; + musicBrainzReleaseArtistId = musicBrainzReleaseArtistIdResult.Value; + } + + return Album.Create( + metadataResult.Value, + Optional.FromNullable(command.MediaFormat), + barcode, + Optional.FromNullable(command.CatalogNumber), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)], + [.. domainTracksResult.Select(trackResult => trackResult.Value)]); + } + + /// + /// 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..d6a3ad44 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMapping.cs @@ -0,0 +1,240 @@ +#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) + { + Result musicBrainzReleaseIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseId.Value); + if (musicBrainzReleaseIdResult.IsFailure) + return musicBrainzReleaseIdResult.Errors; + musicBrainzReleaseId = musicBrainzReleaseIdResult.Value; + } + Optional musicBrainzReleaseGroupId = Optional.None(); + if (repositoryEntity.MusicBrainzReleaseGroupId is not null) + { + Result musicBrainzReleaseGroupIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseGroupId.Value); + if (musicBrainzReleaseGroupIdResult.IsFailure) + return musicBrainzReleaseGroupIdResult.Errors; + musicBrainzReleaseGroupId = musicBrainzReleaseGroupIdResult.Value; + } + Optional musicBrainzReleaseArtistId = Optional.None(); + if (repositoryEntity.MusicBrainzReleaseArtistId is not null) + { + Result musicBrainzReleaseArtistIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzReleaseArtistId.Value); + if (musicBrainzReleaseArtistIdResult.IsFailure) + return musicBrainzReleaseArtistIdResult.Errors; + musicBrainzReleaseArtistId = musicBrainzReleaseArtistIdResult.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..d159dec4 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumMapping.cs @@ -0,0 +1,79 @@ +#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, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, + UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : 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/DeleteAlbumRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeleteAlbumRequestMapping.cs new file mode 100644 index 00000000..ed99467e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeleteAlbumRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Commands.DeleteAlbum; +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 DeleteAlbumRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static DeleteAlbumCommand ToCommand(this DeleteAlbumRequest request) + { + return new DeleteAlbumCommand( + request.AlbumId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequestMapping.cs new file mode 100644 index 00000000..c2d8e3e7 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbum; +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 GetAlbumRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetAlbumQuery ToQuery(this GetAlbumRequest request) + { + return new GetAlbumQuery( + request.AlbumId); + } +} 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..2b2e42c6 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +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 converted query. + public static GetAlbumTracksLiteQuery ToQuery(this GetAlbumTracksLiteRequest request) + { + return new GetAlbumTracksLiteQuery( + request.AlbumId, + request.CurrentPage, + request.PerPage); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequestMapping.cs new file mode 100644 index 00000000..0d0ada2e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Albums.Queries.GetAlbumTracks; +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 GetAlbumTracksRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetAlbumTracksQuery ToQuery(this GetAlbumTracksRequest request) + { + return new GetAlbumTracksQuery( + request.AlbumId); + } +} 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..189313eb --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/UpdateAlbumCommandMapping.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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.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 UpdateAlbumCommandMapping +{ + /// + /// Converts to a domain , preserving the identity and creation metadata of the stored album identified by . + /// + /// The command whose data is used to create the album. + /// The stored album whose identity and creation metadata are preserved. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result ToDomainEntity(this UpdateAlbumCommand command, AlbumEntity existingAlbum) + { + 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) + { + Result musicBrainzReleaseIdResult = MusicBrainzId.Create(command.MusicBrainzReleaseId.Value); + if (musicBrainzReleaseIdResult.IsFailure) + return musicBrainzReleaseIdResult.Errors; + musicBrainzReleaseId = musicBrainzReleaseIdResult.Value; + } + Optional musicBrainzReleaseGroupId = Optional.None(); + if (command.MusicBrainzReleaseGroupId is not null) + { + Result musicBrainzReleaseGroupIdResult = MusicBrainzId.Create(command.MusicBrainzReleaseGroupId.Value); + if (musicBrainzReleaseGroupIdResult.IsFailure) + return musicBrainzReleaseGroupIdResult.Errors; + musicBrainzReleaseGroupId = musicBrainzReleaseGroupIdResult.Value; + } + Optional musicBrainzReleaseArtistId = Optional.None(); + if (command.MusicBrainzReleaseArtistId is not null) + { + Result musicBrainzReleaseArtistIdResult = MusicBrainzId.Create(command.MusicBrainzReleaseArtistId.Value); + if (musicBrainzReleaseArtistIdResult.IsFailure) + return musicBrainzReleaseArtistIdResult.Errors; + musicBrainzReleaseArtistId = musicBrainzReleaseArtistIdResult.Value; + } + + return Album.Create( + AlbumId.Create(existingAlbum.Id), + metadataResult.Value, + Optional.FromNullable(command.MediaFormat), + barcode, + Optional.FromNullable(command.CatalogNumber), + musicBrainzReleaseId, + musicBrainzReleaseGroupId, + musicBrainzReleaseArtistId, + [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)], + [], + existingAlbum.CreatedOnUtc, + Optional.FromNullable(existingAlbum.UpdatedOnUtc)); + } +} 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..41c51009 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/AddArtistCommandMapping.cs @@ -0,0 +1,62 @@ +#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) + { + Result musicBrainzArtistIdResult = MusicBrainzId.Create(command.MusicBrainzArtistId.Value); + if (musicBrainzArtistIdResult.IsFailure) + return musicBrainzArtistIdResult.Errors; + musicBrainzArtistId = musicBrainzArtistIdResult.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..b38cd660 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistEntityMapping.cs @@ -0,0 +1,119 @@ +#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) + { + Result musicBrainzArtistIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzArtistId.Value); + if (musicBrainzArtistIdResult.IsFailure) + return musicBrainzArtistIdResult.Errors; + musicBrainzArtistId = musicBrainzArtistIdResult.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..767b322e --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistMapping.cs @@ -0,0 +1,47 @@ +#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, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, + UpdatedBy = domainEntity.UpdatedOnUtc.HasValue ? Guid.NewGuid() : 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..f5cb79ca --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +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 converted query. + public static GetArtistAlbumsLiteQuery ToQuery(this GetArtistAlbumsLiteRequest request) + { + return new GetArtistAlbumsLiteQuery( + request.ArtistId, + request.CurrentPage, + request.PerPage); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequestMapping.cs new file mode 100644 index 00000000..621fdfef --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtistAlbums; +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 GetArtistAlbumsRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetArtistAlbumsQuery ToQuery(this GetArtistAlbumsRequest request) + { + return new GetArtistAlbumsQuery( + request.ArtistId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequestMapping.cs new file mode 100644 index 00000000..5fe00b9a --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artists.Queries.GetArtist; +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 GetArtistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetArtistQuery ToQuery(this GetArtistRequest request) + { + return new GetArtistQuery( + request.ArtistId); + } +} 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..2527eec0 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +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 converted query. + public static GetArtistsLiteQuery ToQuery(this GetArtistsLiteRequest request) + { + return new GetArtistsLiteQuery( + request.LibraryId, + request.CurrentPage, + request.PerPage, + 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..a0fb4b4c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +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 converted query. + public static GetArtistsQuery ToQuery(this GetArtistsRequest request) + { + return new GetArtistsQuery( + request.LibraryId, + request.CurrentPage, + request.PerPage, + request.SearchTerm); + } +} 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..9aee2609 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistCommandMapping.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +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.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 UpdateArtistCommandMapping +{ + /// + /// Converts to , preserving the identity and creation metadata of the stored artist identified by . + /// + /// The command to be converted. + /// The stored artist whose identity and creation metadata are preserved. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this UpdateArtistCommand command, ArtistEntity existingArtist) + { + // 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) + { + Result musicBrainzArtistIdResult = MusicBrainzId.Create(command.MusicBrainzArtistId.Value); + if (musicBrainzArtistIdResult.IsFailure) + return musicBrainzArtistIdResult.Errors; + musicBrainzArtistId = musicBrainzArtistIdResult.Value; + } + + return Artist.Create( + ArtistId.Create(existingArtist.Id), + LibraryId.Create(existingArtist.LibraryId), + command.Name!, + website, + musicBrainzArtistId, + [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], + [.. domainAlbumsResult.Select(albumResult => albumResult.Value)], + existingArtist.CreatedOnUtc, + Optional.FromNullable(existingArtist.UpdatedOnUtc)); + } +} 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..f413266b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequestMapping.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +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/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..4674d1f2 --- /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..d98cb0fb --- /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..9b8230b0 --- /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..6c9cc533 --- /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..0936cbcd --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/AddTrackCommandMapping.cs @@ -0,0 +1,107 @@ +#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.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> domainIsrcsResult = (command.Isrcs ?? []).ToDomainEntities(); + List errors = [.. domainIsrcsResult.Where(isrcResult => isrcResult.IsFailure).SelectMany(isrcResult => isrcResult.Errors)]; + if (errors.Count > 0) + return errors; + + IEnumerable> domainMoodsResult = (command.Moods ?? []).ToDomainEntities(); + errors = [.. domainMoodsResult.Where(moodResult => moodResult.IsFailure).SelectMany(moodResult => moodResult.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) + { + Result musicBrainzRecordingIdResult = MusicBrainzId.Create(command.MusicBrainzRecordingId.Value); + if (musicBrainzRecordingIdResult.IsFailure) + return musicBrainzRecordingIdResult.Errors; + musicBrainzRecordingId = musicBrainzRecordingIdResult.Value; + } + Optional musicBrainzTrackId = Optional.None(); + if (command.MusicBrainzTrackId is not null) + { + Result musicBrainzTrackIdResult = MusicBrainzId.Create(command.MusicBrainzTrackId.Value); + if (musicBrainzTrackIdResult.IsFailure) + return musicBrainzTrackIdResult.Errors; + musicBrainzTrackId = musicBrainzTrackIdResult.Value; + } + Optional musicBrainzWorkId = Optional.None(); + if (command.MusicBrainzWorkId is not null) + { + Result musicBrainzWorkIdResult = MusicBrainzId.Create(command.MusicBrainzWorkId.Value); + if (musicBrainzWorkIdResult.IsFailure) + return musicBrainzWorkIdResult.Errors; + musicBrainzWorkId = musicBrainzWorkIdResult.Value; + } + + return Track.Create( + command.Path!, + metadataResult.Value, + command.TrackNumber ?? 1, + Optional.FromNullable(command.DiscNumber), + [.. domainIsrcsResult.Select(isrcResult => isrcResult.Value)], + Optional.FromNullable(command.Script), + Optional.FromNullable(command.Key), + Optional.FromNullable(command.Bpm), + [.. domainMoodsResult.Select(moodResult => moodResult.Value)], + Optional.FromNullable(command.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + [.. domainContributorsResult.Select(contributorResult => contributorResult.Value)], + [.. domainRatingsResult.Select(ratingResult => ratingResult.Value)]); + } + + /// + /// 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/DeleteTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeleteTrackRequestMapping.cs new file mode 100644 index 00000000..ff334ad8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeleteTrackRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.DeleteTrack; +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 DeleteTrackRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static DeleteTrackCommand ToCommand(this DeleteTrackRequest request) + { + return new DeleteTrackCommand( + request.TrackId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequestMapping.cs new file mode 100644 index 00000000..9f4e0c92 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +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 GetTrackRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetTrackQuery ToQuery(this GetTrackRequest request) + { + return new GetTrackQuery( + request.TrackId); + } +} 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..ad2ecdb1 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackEntityMapping.cs @@ -0,0 +1,249 @@ +#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) + { + Result musicBrainzRecordingIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzRecordingId.Value); + if (musicBrainzRecordingIdResult.IsFailure) + return musicBrainzRecordingIdResult.Errors; + musicBrainzRecordingId = musicBrainzRecordingIdResult.Value; + } + Optional musicBrainzTrackId = Optional.None(); + if (repositoryEntity.MusicBrainzTrackId is not null) + { + Result musicBrainzTrackIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzTrackId.Value); + if (musicBrainzTrackIdResult.IsFailure) + return musicBrainzTrackIdResult.Errors; + musicBrainzTrackId = musicBrainzTrackIdResult.Value; + } + Optional musicBrainzWorkId = Optional.None(); + if (repositoryEntity.MusicBrainzWorkId is not null) + { + Result musicBrainzWorkIdResult = MusicBrainzId.Create(repositoryEntity.MusicBrainzWorkId.Value); + if (musicBrainzWorkIdResult.IsFailure) + return musicBrainzWorkIdResult.Errors; + musicBrainzWorkId = musicBrainzWorkIdResult.Value; + } + + List domainIsrcs = []; + foreach (Result isrcResult in repositoryEntity.Isrcs.ToDomainEntities()) + { + if (isrcResult.IsFailure) + return isrcResult.Errors; + domainIsrcs.Add(isrcResult.Value); + } + + List domainMoods = []; + foreach (Result moodResult in repositoryEntity.Moods.ToDomainEntities()) + { + if (moodResult.IsFailure) + return moodResult.Errors; + domainMoods.Add(moodResult.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), + domainIsrcs, + Optional.FromNullable(repositoryEntity.Script), + Optional.FromNullable(repositoryEntity.Key), + Optional.FromNullable(repositoryEntity.Bpm), + domainMoods, + Optional.FromNullable(repositoryEntity.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + domainContributors, + domainRatings); + } + + /// + /// 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.Contributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], + [.. repositoryEntity.Ratings.ToResponses()], + [.. repositoryEntity.Moods.ToResponses()], + [.. repositoryEntity.Isrcs.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..3447be59 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackMapping.cs @@ -0,0 +1,82 @@ +#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 = default, + CreatedBy = default + })], + Moods = [.. domainEntity.Moods.ToRepositoryEntities()], + Isrcs = [.. domainEntity.Isrcs.ToRepositoryEntities()], + Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + } +} 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..1f13c50b --- /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.MediaLibrary.AudioLibrary.MusicLibrary.Common; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Commands.UpdateTrack; +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.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; +#endregion + +namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Extension methods for converting . +/// +public static class UpdateTrackCommandMapping +{ + /// + /// Converts to a domain , preserving the provided . + /// + /// The command whose data is used to create the track. + /// The unique identifier of the track. + /// The Id of the media library the track belongs to. + /// The list of ratings of the track. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result ToDomainEntity(this UpdateTrackCommand command, TrackId id, Guid libraryId, List ratings) + { + Result metadataResult = command.Metadata!.ToDomainEntity(); + if (metadataResult.IsFailure) + return metadataResult.Errors; + + Optional musicBrainzRecordingId = Optional.None(); + if (command.MusicBrainzRecordingId is not null) + { + Result musicBrainzRecordingIdResult = MusicBrainzId.Create(command.MusicBrainzRecordingId.Value); + if (musicBrainzRecordingIdResult.IsFailure) + return musicBrainzRecordingIdResult.Errors; + musicBrainzRecordingId = musicBrainzRecordingIdResult.Value; + } + Optional musicBrainzTrackId = Optional.None(); + if (command.MusicBrainzTrackId is not null) + { + Result musicBrainzTrackIdResult = MusicBrainzId.Create(command.MusicBrainzTrackId.Value); + if (musicBrainzTrackIdResult.IsFailure) + return musicBrainzTrackIdResult.Errors; + musicBrainzTrackId = musicBrainzTrackIdResult.Value; + } + Optional musicBrainzWorkId = Optional.None(); + if (command.MusicBrainzWorkId is not null) + { + Result musicBrainzWorkIdResult = MusicBrainzId.Create(command.MusicBrainzWorkId.Value); + if (musicBrainzWorkIdResult.IsFailure) + return musicBrainzWorkIdResult.Errors; + musicBrainzWorkId = musicBrainzWorkIdResult.Value; + } + + List domainIsrcs = []; + foreach (IsrcDto isrc in command.Isrcs ?? []) + { + Result isrcResult = isrc.ToDomainEntity(); + if (isrcResult.IsFailure) + return isrcResult.Errors; + domainIsrcs.Add(isrcResult.Value); + } + + List domainMoods = []; + foreach (MoodDto mood in command.Moods ?? []) + { + Result moodResult = mood.ToDomainEntity(); + if (moodResult.IsFailure) + return moodResult.Errors; + domainMoods.Add(moodResult.Value); + } + + return Track.Create( + id, + command.Path!, + metadataResult.Value, + command.TrackNumber ?? 1, + Optional.FromNullable(command.DiscNumber), + domainIsrcs, + Optional.FromNullable(command.Script), + Optional.FromNullable(command.Key), + Optional.FromNullable(command.Bpm), + domainMoods, + Optional.FromNullable(command.Work), + musicBrainzRecordingId, + musicBrainzTrackId, + musicBrainzWorkId, + [], + ratings); + } +} 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..ad813fec --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/UpdateTrackRequestMapping.cs @@ -0,0 +1,44 @@ +#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.Ratings, + request.Moods, + request.Isrcs); + } +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs index ec7be61c..ba89c298 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookCommandMapping.cs @@ -26,18 +26,19 @@ 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) ?? []]; + 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) ?? []]; + errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsFailure).SelectMany(isbnResult => isbnResult.Errors)]; if (errors.Count > 0) return errors; @@ -45,7 +46,7 @@ public static class AddBookCommandMapping if (metadataResult.IsFailure) return metadataResult.Errors; - // TODO: update Api.Book.md documentation when the functionality is fully implemented. + // TODO: update Api.Books.md documentation when the functionality is fully implemented. BookSeries? bookSeries = null; if (command.Series != null) { @@ -55,13 +56,13 @@ public static class AddBookCommandMapping // 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) ?? []]; + errors = [.. domainContributorsResult.Where(domainContributor => domainContributor.IsFailure).SelectMany(domainContributor => domainContributor.Errors)]; if (errors.Count > 0) return errors; return Book.Create( LibraryId.Create(libraryId), - command.Path, + command.Path!, metadataResult.Value, Optional.FromNullable(command.Format), Optional.FromNullable(command.Edition), 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 767494a0..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 @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Common.Metadata; @@ -61,7 +61,7 @@ public static class BookEntityMapping return bookRatingResult.Errors; List domainContributors = []; - foreach (BookContributorEntity bookContributor in repositoryEntity.BookContributors) + foreach (BookContributorEntity bookContributor in repositoryEntity.Contributors) { Result contributorResult = BookMediaContributor.Create( MediaContributorId.Create(bookContributor.MediaContributorId), bookContributor.Role); @@ -219,14 +219,14 @@ public static class BookEntityMapping repositoryEntity.BarnesAndNobleId, repositoryEntity.AppleBooksId, [.. repositoryEntity.ISBNs.ToResponses()], - [.. repositoryEntity.BookContributors.Select(contributor => new MediaContributorReferenceDto(contributor.MediaContributorId, contributor.Role))], + [.. 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 ); } 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 e537c61d..756cab12 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 @@ -58,7 +58,7 @@ public static class BookMapping BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()], - BookContributors = [.. domainEntity.Contributors.Select(contributor => new BookContributorEntity + Contributors = [.. domainEntity.Contributors.Select(contributor => new BookContributorEntity { Id = Guid.NewGuid(), BookId = domainEntity.Id.Value, 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/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/Common/WrittenContentMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/Common/WrittenContentMetadataDtoMapping.cs new file mode 100644 index 00000000..784c77f8 --- /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/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..f5af960a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommand.cs @@ -0,0 +1,44 @@ +#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 +) : 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..d13ff6cd --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandHandler.cs @@ -0,0 +1,193 @@ +#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.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.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!); + + // 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(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; + + 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 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; + + // 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; + + Result createAlbumResult = command.ToDomainEntity(); + if (createAlbumResult.IsFailure) + return createAlbumResult.Errors; + + AlbumEntity persistenceAlbum = createAlbumResult.Value.ToRepositoryEntity(artistId, libraryId); + Result insertAlbumResult = await _unitOfWork.AlbumRepository.InsertAsync(persistenceAlbum, cancellationToken).ConfigureAwait(false); + if (insertAlbumResult.IsFailure) + return insertAlbumResult.Errors; + + // The pre-insert checks handle the common cases; a concurrent request could still persist an album 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 album as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save. + 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..49c03a9e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/AddAlbum/AddAlbumCommandValidator.cs @@ -0,0 +1,510 @@ +#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.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 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 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 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 ordering and performance characteristics of the track. + 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..87f41cd4 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +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 album to delete. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record DeleteAlbumCommand( + Guid 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..c0bb43e5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandHandler.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.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.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; + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(command.AlbumId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + + // 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(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result deleteAlbumResult = await _unitOfWork.AlbumRepository.DeleteByIdAsync(command.AlbumId, cancellationToken).ConfigureAwait(false); + if (deleteAlbumResult.IsFailure) + return deleteAlbumResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return deleteAlbumResult; + } +} 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..9004db91 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/DeleteAlbum/DeleteAlbumCommandValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(command => command.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty) + .Must(albumId => albumId != Guid.Empty) + .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..27fad9e6 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandHandler.cs @@ -0,0 +1,171 @@ +#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.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.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!); + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, 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 edited + // through another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId) + return Errors.Music.AlbumNotFound; + + // Admins can update the albums of all libraries; for everyone else, only the albums of the libraries they own. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(existingAlbum.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 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; + + Result updateAlbumResult = command.ToDomainEntity(existingAlbum); + if (updateAlbumResult.IsFailure) + return updateAlbumResult.Errors; + + // Map the updated domain album onto a fresh repository entity, ready for the repository to replace the stored data. + AlbumEntity persistenceAlbum = updateAlbumResult.Value.ToRepositoryEntity(existingAlbum.ArtistId, existingAlbum.LibraryId); + + Result updateResult = await _unitOfWork.AlbumRepository.UpdateAsync(persistenceAlbum, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // The repository merges the fresh entity into the tracked stored album and the audit interceptor stamps the update columns, so the + // stored album carries the persisted values, including the audit ones. + return existingAlbum.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..7e4563ba --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Commands/UpdateAlbum/UpdateAlbumCommandValidator.cs @@ -0,0 +1,278 @@ +#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 information, release type and status, disc and track counts, 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!.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); + + 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); + }); + + // 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.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..4fac5407 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQuery.cs @@ -0,0 +1,16 @@ +#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 album to get. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumQuery( + Guid 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..6f7fdf8a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryHandler.cs @@ -0,0 +1,82 @@ +#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; + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(query.AlbumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + 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(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + return getAlbumResult.Value.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..5aa7d43c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbum/GetAlbumQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty) + .Must(albumId => albumId != Guid.Empty) + .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..2462c6f5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQuery.cs @@ -0,0 +1,16 @@ +#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 album whose tracks are retrieved. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumTracksQuery( + Guid 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..2f238094 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryHandler.cs @@ -0,0 +1,83 @@ +#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; + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(query.AlbumId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + 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(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getTracksResult = await _unitOfWork.TrackRepository.GetByAlbumIdAsync(query.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..b826b648 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracks/GetAlbumTracksQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty) + .Must(albumId => albumId != Guid.Empty) + .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..58d4dbc9 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQuery.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.GetAlbumTracksLite; + +/// +/// Query for getting the lightweight read models of all the tracks of an album. +/// +/// The unique identifier of the album whose tracks are retrieved. +/// The page of results to retrieve. +/// The maximum number of tracks to retrieve per page. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumTracksLiteQuery( + Guid AlbumId, + int? CurrentPage, + int? PerPage +) : 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..25692a17 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryHandler.cs @@ -0,0 +1,91 @@ +#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; + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(query.AlbumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + 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(getAlbumResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + PaginationDataDto paginationData = new() + { + CurrentPage = query.CurrentPage ?? 1, + PerPage = query.PerPage ?? 200 + }; + + Result> getTracksResult = await _unitOfWork.TrackRepository.GetTracksLiteByAlbumIdAsync(query.AlbumId, 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..3a241a57 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Albums/Queries/GetAlbumTracksLite/GetAlbumTracksLiteQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty) + .Must(albumId => albumId != Guid.Empty) + .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..1b932e56 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/AddArtist/AddArtistCommandValidator.cs @@ -0,0 +1,547 @@ +#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); + + // 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 ordering and performance characteristics of the track. + 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/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..4f1cda3f --- /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 deleteArtistResult; + } +} 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..e099ed7f --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandHandler.cs @@ -0,0 +1,203 @@ +#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!); + + // Get the existing artist with all its related data. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(artistId, 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; + + // Convert the command to a domain aggregate to enforce invariants, preserving the identity and creation metadata of the stored artist. + Result updateArtistResult = command.ToDomainEntity(existingArtist); + 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..be3d1b5d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Commands/UpdateArtist/UpdateArtistCommandValidator.cs @@ -0,0 +1,557 @@ +#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 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); + + // 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 ordering and performance characteristics of the track. + 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/Artists/Queries/GetArtist/GetArtistQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQuery.cs new file mode 100644 index 00000000..c73b7f00 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQuery.cs @@ -0,0 +1,16 @@ +#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 artist to get. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistQuery( + Guid 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..35241f6c --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryHandler.cs @@ -0,0 +1,82 @@ +#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; + + // Admins can see all artists; for everyone else, only the artists of the libraries they own. + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(query.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + return Errors.Music.ArtistNotFound; + + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(getArtistResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + return getArtistResult.Value.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..7574751d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtist/GetArtistQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .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..67c81e24 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQuery.cs @@ -0,0 +1,16 @@ +#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 artist whose albums are retrieved. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistAlbumsQuery( + Guid 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..566a95cc --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryHandler.cs @@ -0,0 +1,83 @@ +#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; + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(query.ArtistId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + 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(getArtistResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getAlbumsResult = await _unitOfWork.AlbumRepository.GetByArtistIdAsync(query.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..85724d04 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbums/GetArtistAlbumsQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty) + .Must(artistId => artistId != Guid.Empty) + .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..09644e9d --- /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 System; +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 artist whose albums are retrieved. +/// The page of results to retrieve. +/// The maximum number of albums to retrieve per page. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistAlbumsLiteQuery( + Guid ArtistId, + int? CurrentPage, + int? PerPage +) : 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..1f15a8c7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryHandler.cs @@ -0,0 +1,91 @@ +#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; + + Result getArtistResult = await _unitOfWork.ArtistRepository.GetByIdAsync(query.ArtistId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getArtistResult.IsFailure) + return getArtistResult.Errors; + if (getArtistResult.Value is null) + 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(getArtistResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + PaginationDataDto paginationData = new() + { + CurrentPage = query.CurrentPage ?? 1, + PerPage = query.PerPage ?? 200 + }; + + Result> getAlbumsResult = await _unitOfWork.AlbumRepository.GetAlbumsLiteByArtistIdAsync(query.ArtistId, 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..b001cfe0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistAlbumsLite/GetArtistAlbumsLiteQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty) + .Must(artistId => artistId != Guid.Empty) + .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..b12c9967 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQuery.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.Artists.Queries.GetArtists; + +/// +/// Query for getting all the artists of a media library. +/// +/// The Id of the media library whose artists are retrieved. +/// The page of results to retrieve. +/// The maximum number of artists to retrieve per page. +/// The search term used to filter the artists by name. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetArtistsQuery( + Guid LibraryId, + int? CurrentPage, + int? PerPage, + 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..595c4a90 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryHandler.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.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; + + // 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(query.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + PaginationDataDto paginationData = new() + { + CurrentPage = query.CurrentPage ?? 1, + PerPage = query.PerPage ?? 200 + }; + + LibraryFilterDto libraryFilter = new() + { + LibraryId = query.LibraryId, + SearchTerm = query.SearchTerm + }; + + Result> getArtistsResult = await _unitOfWork.ArtistRepository + .GetAllAsync(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..9efe8c76 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtists/GetArtistsQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(libraryId => libraryId != Guid.Empty) + .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..9ece1b87 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQuery.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.Artists.Queries.GetArtistsLite; + +/// +/// Query for getting the lightweight read models of all the artists of a media library. +/// +/// The Id of the media library whose artists are retrieved. +/// The page of results to retrieve. +/// The maximum number of artists to retrieve per page. +/// The search term used to filter the artists by name. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public record GetArtistsLiteQuery( + Guid LibraryId, + int? CurrentPage, + int? PerPage, + 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..df487147 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryHandler.cs @@ -0,0 +1,92 @@ +#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; + + // 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(query.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + PaginationDataDto paginationData = new() + { + CurrentPage = query.CurrentPage ?? 1, + PerPage = query.PerPage ?? 200 + }; + LibraryFilterDto filter = new() + { + LibraryId = query.LibraryId, + SearchTerm = query.SearchTerm + }; + + Result> getArtistsResult = await _unitOfWork.ArtistRepository.GetAllLiteAsync( + 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..c1d6c1a0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Artists/Queries/GetArtistsLite/GetArtistsLiteQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty) + .Must(libraryId => libraryId != Guid.Empty) + .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..38737506 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommand.cs @@ -0,0 +1,56 @@ +#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 +) : 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..06d0d967 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandHandler.cs @@ -0,0 +1,193 @@ +#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.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.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!); + + // 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(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // 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; + + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null) + return Errors.Music.AlbumNotFound; + + // Resource scoping: the track must belong to an album of the artist and library named by the route, so that a track can never be added + // through another library's or artist's route; the mismatch is reported as not found, without disclosing that the album exists elsewhere. + if (getAlbumResult.Value.LibraryId != libraryId || getAlbumResult.Value.ArtistId != artistId) + return Errors.Music.AlbumNotFound; + + // 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; + + Result createTrackResult = command.ToDomainEntity(); + if (createTrackResult.IsFailure) + return createTrackResult.Errors; + + TrackEntity persistenceTrack = createTrackResult.Value.ToRepositoryEntity(albumId, libraryId); + Result insertTrackResult = await _unitOfWork.TrackRepository.InsertAsync(persistenceTrack, cancellationToken).ConfigureAwait(false); + if (insertTrackResult.IsFailure) + return insertTrackResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Returns the track as it was actually persisted, instead of the in-memory aggregate, so the response reflects every value the database applied on save. + Result getPersistedTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(persistenceTrack.Id, 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..c71c4d22 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/AddTrack/AddTrackCommandValidator.cs @@ -0,0 +1,284 @@ +#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); + }); + + 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) + .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 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..23d3998a --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommand.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +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 track to delete. +[DebuggerDisplay("TrackId: {TrackId}")] +public record DeleteTrackCommand( + Guid 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..9f47fc6e --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandHandler.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.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.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; + + Result getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(command.TrackId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return Errors.Music.TrackNotFound; + + // 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(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result deleteTrackResult = await _unitOfWork.TrackRepository.DeleteByIdAsync(command.TrackId, cancellationToken).ConfigureAwait(false); + if (deleteTrackResult.IsFailure) + return deleteTrackResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + return deleteTrackResult; + } +} 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..01964b31 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/DeleteTrack/DeleteTrackCommandValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(command => command.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty) + .Must(trackId => trackId != Guid.Empty) + .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..732afa65 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommand.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Contracts.DTO.Common; +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 ratings for this track. +/// The list of moods of the track. +/// The list of ISRC of the 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? Ratings, + List? Moods, + List? Isrcs +) : 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..311bb522 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandHandler.cs @@ -0,0 +1,150 @@ +#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.Common.Metadata; +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; +using Lumina.Contracts.DTO.Common; +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.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.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; + + /// + /// 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 UpdateTrackCommandHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + { + _unitOfWork = unitOfWork; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// 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!); + + Result getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(trackId, 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 library and the album named by the route, so that a track can never be edited + // through another library's or album's route; the mismatch is reported as not found, without disclosing that the track exists elsewhere. + if (existingTrack.LibraryId != libraryId || existingTrack.AlbumId != albumId) + return Errors.Music.TrackNotFound; + + // 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(existingTrack.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The track must also belong to the artist named by the route, which is stored on the album of the track. + Result getAlbumResult = await _unitOfWork.AlbumRepository.GetByIdAsync(albumId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getAlbumResult.IsFailure) + return getAlbumResult.Errors; + if (getAlbumResult.Value is null || getAlbumResult.Value.ArtistId != artistId) + 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; + + List domainRatings = []; + List domainRatingsErrors = []; + foreach (AudioRatingDto rating in command.Ratings ?? []) + { + Result ratingResult = rating.ToDomainEntity(); + if (ratingResult.IsFailure) + domainRatingsErrors.AddRange(ratingResult.Errors); + else + domainRatings.Add(ratingResult.Value); + } + if (domainRatingsErrors.Count > 0) + return domainRatingsErrors; + + Result updatedTrackResult = command.ToDomainEntity(TrackId.Create(existingTrack.Id), existingTrack.LibraryId, domainRatings); + if (updatedTrackResult.IsFailure) + return updatedTrackResult.Errors; + + // Map the updated domain track onto a fresh repository entity, ready for the repository to replace the stored data. + TrackEntity persistenceTrack = updatedTrackResult.Value.ToRepositoryEntity(existingTrack.AlbumId, existingTrack.LibraryId); + + Result updateResult = await _unitOfWork.TrackRepository.UpdateAsync(persistenceTrack, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // The repository merges the fresh entity into the tracked stored track and the audit interceptor stamps the update columns, so the + // stored track carries the persisted values, including the audit ones. + return existingTrack.ToResponse(); + } +} 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..ecc418e7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Commands/UpdateTrack/UpdateTrackCommandValidator.cs @@ -0,0 +1,275 @@ +#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); + }); + + 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) + .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 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..8c3ad79d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQuery.cs @@ -0,0 +1,16 @@ +#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 track to get. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetTrackQuery( + Guid 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..a6f1bfef --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryHandler.cs @@ -0,0 +1,82 @@ +#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.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; + + Result getTrackResult = await _unitOfWork.TrackRepository.GetByIdAsync(query.TrackId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + 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(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + return getTrackResult.Value.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..1a800cd5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrack/GetTrackQueryValidator.cs @@ -0,0 +1,26 @@ +#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() + { + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty) + .Must(trackId => trackId != Guid.Empty) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} 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 0f638ce5..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 @@ -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( string? LibraryId, - string Path, + string? Path, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, 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 61c27bc7..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 @@ -88,7 +88,7 @@ public class AddBookCommandHandler : ICommandHandler _pathService.IsPathWithin(command.Path, contentLocation.Path))) + if (!getLibraryResult.Value.ContentLocations.Any(contentLocation => _pathService.IsPathWithin(command.Path!, contentLocation.Path))) return DomainErrors.WrittenContent.BookPathMustBeWithinLibraryContentLocations; // Media contributors are referenced by Id and are never created implicitly by adding a book, so each one must already exist. 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 321bbc66..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 @@ -126,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) @@ -156,7 +155,8 @@ public class AddBookCommandValidator : AbstractValidator .When(m => m!.Language is not null); metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode) - .NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) + .NotEmpty() + .WithError(Errors.Metadata.LanguageCodeCannotBeEmpty) .Length(2) .WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong) .When(m => m!.OriginalLanguage is not null); @@ -291,7 +291,7 @@ public class AddBookCommandValidator : AbstractValidator // Validates the media contributors that contributed to the book. RuleFor(command => command.Contributors) .NotNull() - .WithError(Errors.WrittenContent.ContributorsListCannotBeNull); + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); RuleForEach(command => command.Contributors) .ChildRules(contributor => 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 c5f65dec..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 @@ -31,7 +31,7 @@ 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( 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 8a2582f2..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 ===================================================================================== +#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; @@ -90,6 +91,13 @@ public class UpdateBookCommandHandler : ICommandHandler 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; + // 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) @@ -103,13 +111,6 @@ public class UpdateBookCommandHandler : ICommandHandler updateResult = await _unitOfWork.BookRepository.UpdateAsync(updatedBook, cancellationToken).ConfigureAwait(false); if (updateResult.IsFailure) return updateResult.Errors; 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 9b9715aa..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 @@ -246,19 +246,17 @@ 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+$") @@ -295,7 +293,7 @@ public class UpdateBookCommandValidator : AbstractValidator // Validates the media contributors that contributed to the book. RuleFor(command => command.Contributors) .NotNull() - .WithError(Errors.WrittenContent.ContributorsListCannotBeNull); + .WithError(Errors.MediaContributor.ContributorsListCannotBeNull); RuleForEach(command => command.Contributors) .ChildRules(contributor => 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/GetBooks/GetBooksQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Queries/GetBooks/GetBooksQueryHandler.cs index 37e02511..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; 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 f3b734ae..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 @@ -2,7 +2,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DTO.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; 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 0eff4157..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 @@ -28,8 +28,8 @@ public class GetBooksLiteQueryValidator : AbstractValidator .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 + // 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 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/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/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.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/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/DeleteAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeleteAlbumRequest.cs new file mode 100644 index 00000000..2e9828a5 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/DeleteAlbumRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a request to delete an album by the specified Id. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album to delete. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record DeleteAlbumRequest( + Guid ArtistId, + Guid AlbumId +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequest.cs new file mode 100644 index 00000000..b834f728 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a request to get an album by the specified Id. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album to retrieve. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumRequest( + Guid ArtistId, + Guid AlbumId +); 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..e6560abd --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLiteRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +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 unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album whose tracks are retrieved. +/// The page of results to retrieve. Optional. +/// The maximum number of tracks to retrieve per page. Optional. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumTracksLiteRequest( + Guid ArtistId, + Guid AlbumId, + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequest.cs new file mode 100644 index 00000000..aa1bdaa3 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksRequest.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; + +/// +/// Represents a request to get the tracks of an album. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. +/// The unique identifier of the album whose tracks are retrieved. +[DebuggerDisplay("AlbumId: {AlbumId}")] +public record GetAlbumTracksRequest( + Guid ArtistId, + Guid AlbumId +); 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..24c756e9 --- /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. Optional. +/// 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..7e3a4553 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLiteRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +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 unique identifier of the artist whose albums are retrieved. +/// The page of results to retrieve. Optional. +/// The maximum number of albums to retrieve per page. Optional. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistAlbumsLiteRequest( + Guid ArtistId, + int? CurrentPage, + int? PerPage +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequest.cs new file mode 100644 index 00000000..7d4143ba --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to get the albums of an artist. +/// +/// The unique identifier of the artist whose albums are retrieved. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistAlbumsRequest( + Guid ArtistId +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequest.cs new file mode 100644 index 00000000..a8bf3cc8 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to get an artist by the specified Id. +/// +/// The unique identifier of the artist to retrieve. +[DebuggerDisplay("ArtistId: {ArtistId}")] +public record GetArtistRequest( + Guid ArtistId +); 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..f6f3b1f2 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsLiteRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +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 Id of the media library whose artists are retrieved. Required. +/// 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("LibraryId: {LibraryId}")] +public record GetArtistsLiteRequest( + Guid LibraryId, + 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..2719f39d --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/GetArtistsRequest.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; + +/// +/// Represents a request to get the artists of a media library. +/// +/// The Id of the media library whose artists are retrieved. Required. +/// 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("LibraryId: {LibraryId}")] +public record GetArtistsRequest( + Guid LibraryId, + int? CurrentPage, + int? PerPage, + string? SearchTerm +); 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..19f60afa --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Artists/UpdateArtistRequest.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 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/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/DeleteTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeleteTrackRequest.cs new file mode 100644 index 00000000..150405a6 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/DeleteTrackRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to delete a track by the specified Id. +/// +/// 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. +[DebuggerDisplay("TrackId: {TrackId}")] +public record DeleteTrackRequest( + Guid ArtistId, + Guid AlbumId, + Guid TrackId +); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequest.cs new file mode 100644 index 00000000..a96be026 --- /dev/null +++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/GetTrackRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to get a track by the specified Id. +/// +/// 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 retrieve. +[DebuggerDisplay("TrackId: {TrackId}")] +public record GetTrackRequest( + Guid ArtistId, + Guid AlbumId, + Guid TrackId +); 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..11c98e73 --- /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 media contributors that performed on the track. Optional. +/// The list of ratings for this track. Required. +/// The list of moods of the track. Optional. +/// The list of ISRC (International Standard Recording Code) of the track. Optional. +[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? Contributors, + List? Ratings, + List? Moods, + List? Isrcs +); 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 59d33a09..0de7c352 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs @@ -33,7 +33,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// The list of ratings for this book. Required. [DebuggerDisplay("Title: {Metadata.Title}")] public record AddBookRequest( - string Path, + string? Path, WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, 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/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..347b46e2 --- /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 references to the media contributors that performed on the track, each with the role they played. +/// The list of ratings for this track. +/// The list of moods of the track. +/// The list of ISRC (International Standard Recording Code) of the 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? Contributors, + List? Ratings, + List? Moods, + List? Isrcs +); 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 48a31027..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); diff --git a/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/TrackConfiguration.cs new file mode 100644 index 00000000..c96b0d1a --- /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.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.HasMany(track => track.Contributors) + .WithOne() + .HasForeignKey(contributor => contributor.TrackId) + .OnDelete(DeleteBehavior.Cascade); + + 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.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/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs similarity index 91% rename from src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs rename to src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index 9bd6f22e..67db1876 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -2,12 +2,12 @@ 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.Core.Repositories.BookLibrary.Specifications; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -25,7 +25,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.Core.Repositories.Books; +namespace Lumina.DataAccess.Core.Repositories.BookLibrary; /// /// Repository for books. @@ -55,13 +55,13 @@ 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; // 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 bookPathExists = await _luminaDbContext.Books.AnyAsync(repositoryBook => repositoryBook.LibraryId == book.LibraryId && repositoryBook.Path == book.Path, cancellationToken: cancellationToken).ConfigureAwait(false); - if (bookPathExists) + 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; // Fetch existing tags and genres. @@ -87,20 +87,20 @@ 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, bool includeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) + public async Task> GetByIdAsync(Guid id, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) { IQueryable query = _luminaDbContext.Books; if (!shouldTrackEntities) query = query.AsNoTracking(); - if (includeNavigationProperties) + if (shouldIncludeNavigationProperties) { query = query .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) - .Include(book => book.BookArtwork); + .Include(book => book.Contributors) + .Include(book => book.Artwork); } return await query.FirstOrDefaultAsync(book => book.Id == id, cancellationToken).ConfigureAwait(false); } @@ -113,24 +113,24 @@ internal sealed class BookRepository : IBookRepository /// 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 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 includeNavigationProperties = true, bool shouldTrackEntities = true, 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; if (!shouldTrackEntities) booksQuery = booksQuery.AsNoTracking(); - if (includeNavigationProperties) + if (shouldIncludeNavigationProperties) { booksQuery = booksQuery .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) - .Include(book => book.BookArtwork); + .Include(book => book.Contributors) + .Include(book => book.Artwork); } // Books should always be retrieved only per owning libraries. @@ -190,11 +190,11 @@ internal sealed class BookRepository : IBookRepository /// 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 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 includeNavigationProperties = false, bool shouldTrackEntities = false, CancellationToken cancellationToken = default) where TFilter : BaseFilterDto + 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) @@ -204,15 +204,15 @@ internal sealed class BookRepository : IBookRepository IQueryable booksQuery = _luminaDbContext.Books; if (!shouldTrackEntities) booksQuery = booksQuery.AsNoTracking(); - if (includeNavigationProperties) + if (shouldIncludeNavigationProperties) { booksQuery = booksQuery .Include(book => book.Tags) .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) - .Include(book => book.BookArtwork); + .Include(book => book.Contributors) + .Include(book => book.Artwork); } booksQuery = booksQuery.Where(book => book.LibraryId == libraryFilter.LibraryId); @@ -229,7 +229,7 @@ internal sealed class BookRepository : IBookRepository Id = book.Id, Title = book.Title, ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear, - CoverPath = book.BookArtwork + CoverPath = book.Artwork .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) .FirstOrDefault() @@ -281,8 +281,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.BookArtwork) + .Include(book => book.Contributors) + .Include(book => book.Artwork) .Where(book => book.LibraryId == libraryId) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -300,7 +300,7 @@ 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) .FirstOrDefaultAsync(book => book.LibraryId == libraryId && book.Path == path, cancellationToken).ConfigureAwait(false); } @@ -319,7 +319,7 @@ 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) .Where(book => book.LibraryId == libraryId && book.MetadataStatus != MetadataStatus.Enriched && (lastPath == null || book.Path.CompareTo(lastPath) > 0)) @@ -355,9 +355,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.Artwork) .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) @@ -374,7 +374,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); } @@ -466,15 +466,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; @@ -495,8 +495,7 @@ internal sealed class BookRepository : IBookRepository .Include(book => book.Genres) .Include(book => book.ISBNs) .Include(book => book.Ratings) - .Include(book => book.BookContributors) - .Include(book => book.BookArtwork) + .Include(book => book.Contributors) .FirstOrDefaultAsync(book => book.Id == data.Id, cancellationToken).ConfigureAwait(false); if (foundBook is null) return Errors.WrittenContent.BookNotFound; @@ -538,10 +537,8 @@ internal sealed class BookRepository : IBookRepository foundBook.ISBNs.AddRange(data.ISBNs); foundBook.Ratings.Clear(); foundBook.Ratings.AddRange(data.Ratings); - foundBook.BookContributors.Clear(); - foundBook.BookContributors.AddRange(data.BookContributors); - foundBook.BookArtwork.Clear(); - foundBook.BookArtwork.AddRange(data.BookArtwork); + foundBook.Contributors.Clear(); + foundBook.Contributors.AddRange(data.Contributors); return Result.Updated; } 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 95% rename from src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookSearchSpecification.cs rename to src/Lumina.DataAccess/Core/Repositories/BookLibrary/Specifications/BookSearchSpecification.cs index 18cb7e22..87ce81b3 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. 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..56e89fbc --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -0,0 +1,269 @@ +#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.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; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public AlbumRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// 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; + + // Fetch the tags and genres referenced anywhere in the aggregate, so that the shared tables are not duplicated. + List tagNames = [.. album.Tags.Select(tag => tag.Name!) + .Concat(album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!))) + .Distinct()]; + List genreNames = [.. album.Genres.Select(genre => genre.Name!) + .Concat(album.Tracks.SelectMany(track => track.Genres.Select(genre => genre.Name!))) + .Distinct()]; + + List existingTags = await _luminaDbContext.Set() + .Where(tag => tagNames.Contains(tag.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => genreNames.Contains(genre.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + // Replace the tags and genres of the album and of its tracks with the existing ones, so that the shared tables are not duplicated. + album.Tags = [.. album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; + album.Genres = [.. album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; + + foreach (TrackEntity track in album.Tracks) + { + track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; + track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; + } + + _luminaDbContext.Albums.Add(album); + return Result.Created; + } + + /// + /// Updates an existing album, replacing its editable data while preserving its identity and 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 album, CancellationToken cancellationToken) + { + AlbumEntity? foundAlbum = await _luminaDbContext.Albums + .Include(repositoryAlbum => repositoryAlbum.Tags) + .Include(repositoryAlbum => repositoryAlbum.Genres) + .Include(repositoryAlbum => repositoryAlbum.Contributors) + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == album.Id, cancellationToken).ConfigureAwait(false); + if (foundAlbum is null) + return Errors.Music.AlbumNotFound; + + // The stored identity and audit columns are never overwritten by an edit. + Guid artistId = foundAlbum.ArtistId; + Guid libraryId = foundAlbum.LibraryId; + DateTime createdOnUtc = foundAlbum.CreatedOnUtc; + Guid createdBy = foundAlbum.CreatedBy; + + // Copy the editable scalar properties of the album, ignoring the unchanged collection columns. + _luminaDbContext.Entry(foundAlbum).CurrentValues.SetValues(album); + foundAlbum.ArtistId = artistId; + foundAlbum.LibraryId = libraryId; + foundAlbum.CreatedOnUtc = createdOnUtc; + foundAlbum.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 => album.Tags.Select(albumTag => albumTag.Name).Contains(tag.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => album.Genres.Select(albumGenre => albumGenre.Name).Contains(genre.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + foundAlbum.Tags.Clear(); + foundAlbum.Tags.UnionWith(album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); + foundAlbum.Genres.Clear(); + foundAlbum.Genres.UnionWith(album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + + // Replace the owned ratings and contributors collections of the album, so that removed entries are deleted and new entries are inserted. + foundAlbum.Ratings.Clear(); + foundAlbum.Ratings.AddRange(album.Ratings); + foundAlbum.Contributors.Clear(); + foundAlbum.Contributors.AddRange(album.Contributors); + + 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); + } + + /// + /// Deletes the album identified by . + /// + /// The Id of the album to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + AlbumEntity? album = await _luminaDbContext.Albums + .FirstOrDefaultAsync(repositoryAlbum => repositoryAlbum.Id == id, cancellationToken).ConfigureAwait(false); + if (album is null) + return Errors.Music.AlbumNotFound; + + _luminaDbContext.Albums.Remove(album); + return Result.Deleted; + } + + /// + /// Gets 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..7728337e --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -0,0 +1,362 @@ +#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.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; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ArtistRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// 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; + + // Fetch the tags and genres referenced anywhere in the aggregate, so that the shared tables are not duplicated. + List tagNames = [.. artist.Albums + .SelectMany(album => album.Tags.Select(tag => tag.Name!)) + .Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Tags.Select(tag => tag.Name!)))) + .Distinct()]; + List genreNames = [.. artist.Albums + .SelectMany(album => album.Genres.Select(genre => genre.Name!)) + .Concat(artist.Albums.SelectMany(album => album.Tracks.SelectMany(track => track.Genres.Select(genre => genre.Name!)))) + .Distinct()]; + + List existingTags = await _luminaDbContext.Set() + .Where(tag => tagNames.Contains(tag.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => genreNames.Contains(genre.Name!)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + // Replace the tags and genres of every album and track of the aggregate with the existing ones, so that the shared tables are not duplicated. + foreach (AlbumEntity album in artist.Albums) + { + album.Tags = [.. album.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; + album.Genres = [.. album.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; + + foreach (TrackEntity track in album.Tracks) + { + track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; + track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; + } + } + + _luminaDbContext.Artists.Add(artist); + return Result.Created; + } + + /// + /// Updates an existing artist. + /// + /// The artist to update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateAsync(ArtistEntity artist, CancellationToken cancellationToken) + { + ArtistEntity? foundArtist = await _luminaDbContext.Artists + .Include(repositoryArtist => repositoryArtist.Contributors) + .Include(repositoryArtist => repositoryArtist.Albums) + .ThenInclude(album => album.Tracks) + .FirstOrDefaultAsync(repositoryArtist => repositoryArtist.Id == artist.Id, cancellationToken).ConfigureAwait(false); + if (foundArtist is null) + return Errors.Music.ArtistNotFound; + + // The stored identity and audit columns are never overwritten by an edit. + Guid libraryId = foundArtist.LibraryId; + DateTime createdOnUtc = foundArtist.CreatedOnUtc; + Guid createdBy = foundArtist.CreatedBy; + + // Copy the editable scalar properties of the artist, ignoring the unchanged collection columns. + _luminaDbContext.Entry(foundArtist).CurrentValues.SetValues(artist); + foundArtist.LibraryId = libraryId; + foundArtist.CreatedOnUtc = createdOnUtc; + foundArtist.CreatedBy = createdBy; + + // Replace the owned collections of the artist, so that removed entries are deleted and new entries are inserted. + foundArtist.Contributors.Clear(); + foundArtist.Contributors.AddRange(artist.Contributors); + foundArtist.Albums.Clear(); + foundArtist.Albums.AddRange(artist.Albums); + + 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); + + if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) + artistsQuery = artistsQuery.Where(artist => artist.Name.ToLower().Contains(libraryFilter.SearchTerm.ToLower())); + + IQueryable orderedArtistsQuery = artistsQuery.OrderBy(artist => artist.Name).ThenBy(artist => artist.Id); + + // 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); + } + + artistsQuery = artistsQuery.Where(artist => artist.LibraryId == libraryFilter.LibraryId); + + if (!string.IsNullOrWhiteSpace(libraryFilter.SearchTerm)) + artistsQuery = artistsQuery.Where(artist => artist.Name.ToLower().Contains(libraryFilter.SearchTerm.ToLower())); + + IQueryable liteRowsQuery = artistsQuery + .OrderBy(artist => artist.Name) + .ThenBy(artist => artist.Id) + .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 + }; + } +} 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..3d957bbe --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -0,0 +1,247 @@ +#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.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. + bool doesTrackPathExist = await _luminaDbContext.Tracks.AnyAsync(repositoryTrack => repositoryTrack.LibraryId == track.LibraryId && repositoryTrack.Path == track.Path, cancellationToken: cancellationToken).ConfigureAwait(false); + if (doesTrackPathExist) + return Errors.Music.TrackAlreadyExists; + + // Fetch existing tags and genres. + List existingTags = await _luminaDbContext.Set() + .Where(tag => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + // Replace tags and genres in the track with existing ones, so that the shared tables are not duplicated. + track.Tags = [.. track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)]; + track.Genres = [.. track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)]; + + _luminaDbContext.Tracks.Add(track); + return Result.Created; + } + + /// + /// Updates an existing track, replacing its editable data while preserving its identity and 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 track, CancellationToken cancellationToken) + { + TrackEntity? foundTrack = await _luminaDbContext.Tracks + .Include(repositoryTrack => repositoryTrack.Tags) + .Include(repositoryTrack => repositoryTrack.Genres) + .Include(repositoryTrack => repositoryTrack.Contributors) + .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == track.Id, cancellationToken).ConfigureAwait(false); + if (foundTrack is null) + return Errors.Music.TrackNotFound; + + // The stored identity and audit columns are never overwritten by an edit. + Guid albumId = foundTrack.AlbumId; + Guid libraryId = foundTrack.LibraryId; + DateTime createdOnUtc = foundTrack.CreatedOnUtc; + Guid createdBy = foundTrack.CreatedBy; + + // Copy the editable scalar properties of the track, ignoring the unchanged collection columns. + _luminaDbContext.Entry(foundTrack).CurrentValues.SetValues(track); + foundTrack.AlbumId = albumId; + foundTrack.LibraryId = libraryId; + foundTrack.CreatedOnUtc = createdOnUtc; + foundTrack.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 => track.Tags.Select(trackTag => trackTag.Name).Contains(tag.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + List existingGenres = await _luminaDbContext.Set() + .Where(genre => track.Genres.Select(trackGenre => trackGenre.Name).Contains(genre.Name)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + foundTrack.Tags.Clear(); + foundTrack.Tags.UnionWith(track.Tags.Select(tag => existingTags.FirstOrDefault(existingTag => existingTag.Name == tag.Name) ?? tag)); + foundTrack.Genres.Clear(); + foundTrack.Genres.UnionWith(track.Genres.Select(genre => existingGenres.FirstOrDefault(existingGenre => existingGenre.Name == genre.Name) ?? genre)); + + // Replace the owned collections of the track, so that removed entries are deleted and new entries are inserted. + foundTrack.Ratings.Clear(); + foundTrack.Ratings.AddRange(track.Ratings); + foundTrack.Contributors.Clear(); + foundTrack.Contributors.AddRange(track.Contributors); + foundTrack.Moods.Clear(); + foundTrack.Moods.AddRange(track.Moods); + foundTrack.Isrcs.Clear(); + foundTrack.Isrcs.AddRange(track.Isrcs); + + 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); + } + return await query.FirstOrDefaultAsync(track => track.Id == id, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes the track identified by . + /// + /// The Id of the track to delete. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByIdAsync(Guid id, CancellationToken cancellationToken) + { + TrackEntity? track = await _luminaDbContext.Tracks + .FirstOrDefaultAsync(repositoryTrack => repositoryTrack.Id == id, cancellationToken).ConfigureAwait(false); + if (track is null) + return Errors.Music.TrackNotFound; + + _luminaDbContext.Tracks.Remove(track); + return Result.Deleted; + } + + /// + /// 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) + .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.Domain/Common/Errors/Errors.MediaContributor.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs index d63ffa89..87d4bf7b 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.MediaContributor.cs @@ -19,6 +19,7 @@ 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/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs index f9227955..d3ecfc57 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Artist.cs @@ -2,7 +2,7 @@ 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.Core.BoundedContexts.AudioLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; using System; @@ -16,16 +16,21 @@ 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. /// [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 +47,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,31 +60,31 @@ 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; @@ -93,35 +93,37 @@ public sealed class Artist : AggregateRoot /// /// 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 +131,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 +144,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 +192,42 @@ 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); + _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 = DateTime.UtcNow; + return Result.Updated; } } 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..c9e98b73 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.HasValue ? updatedOnUtc.Value : null; } /// @@ -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); } /// @@ -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. + public 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. + public 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. + public 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 = 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..ce0308d7 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 @@ -20,14 +21,9 @@ public sealed class Track : Entity { private readonly List _isrcs; private readonly List _moods; - private readonly List _credits; + 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,7 +103,6 @@ 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. @@ -121,11 +116,10 @@ public sealed class Track : Entity /// 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. private Track( TrackId id, - LibraryId libraryId, string path, AudioMetadata metadata, int trackNumber, @@ -139,11 +133,10 @@ public sealed class Track : Entity Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, + List contributors, List ratings) : base(id) { Id = id; - LibraryId = libraryId; Path = path; Metadata = metadata; TrackNumber = trackNumber; @@ -157,14 +150,13 @@ public sealed class Track : Entity MusicBrainzRecordingId = musicBrainzRecordingId; MusicBrainzTrackId = musicBrainzTrackId; MusicBrainzWorkId = musicBrainzWorkId; - _credits = credits; + _contributors = contributors; _ratings = ratings; } /// /// 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. @@ -178,13 +170,12 @@ public sealed class Track : Entity /// 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, @@ -198,12 +189,11 @@ public sealed class Track : Entity Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, + List contributors, List ratings) { return new Track( TrackId.CreateUnique(), - libraryId, path, metadata, trackNumber, @@ -217,7 +207,7 @@ public sealed class Track : Entity musicBrainzRecordingId, musicBrainzTrackId, musicBrainzWorkId, - credits, + contributors, ratings); } @@ -225,7 +215,6 @@ public sealed class Track : Entity /// 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. @@ -239,14 +228,13 @@ public sealed class Track : Entity /// 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( TrackId id, - LibraryId libraryId, string path, AudioMetadata metadata, int trackNumber, @@ -260,12 +248,11 @@ public sealed class Track : Entity Optional musicBrainzRecordingId, Optional musicBrainzTrackId, Optional musicBrainzWorkId, - List credits, + List contributors, List ratings) { return new Track( id, - libraryId, path, metadata, trackNumber, @@ -279,18 +266,72 @@ public sealed class Track : Entity musicBrainzRecordingId, musicBrainzTrackId, musicBrainzWorkId, - credits, + contributors, ratings); } /// - /// Replaces the credits of the media contributors of the track with the provided . + /// Replaces the media contributors of the track with the provided . /// - /// The credits of the media contributors of the track. - public void UpdateCredits(IReadOnlyCollection credits) + /// The media contributors of the track. + public 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 track with the provided . + /// + /// The ratings of the track. + public 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. + public 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 = DateTime.UtcNow; + return Result.Updated; } } 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..0663c63c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicBrainzId.cs @@ -36,6 +36,9 @@ public sealed class MusicBrainzId : ValueObject /// The created instance. public static Result Create(Guid value) { + if (value == Guid.Empty) + return Errors.Music.MusicBrainzIdInvalidFormat; + return new MusicBrainzId(value); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index e46c330e..8fab9f39 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; @@ -190,7 +187,7 @@ public sealed class Book : AggregateRoot CreatedOnUtc = createdOnUtc; UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null; _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,7 +234,7 @@ public sealed class Book : AggregateRoot Optional barnesAndNobleId, Optional appleBooksId, List isbns, - List contributors, + IEnumerable contributors, List ratings) { // TODO: enforce invariants @@ -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,7 +313,7 @@ public sealed class Book : AggregateRoot DateTime createdOnUtc, Optional updatedOnUtc, List isbns, - List contributors, + IEnumerable contributors, List ratings) { // TODO: enforce invariants @@ -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 _contributors.Clear(); - _contributors.AddRange(contributors); + _contributors.UnionWith(contributors); } /// 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.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.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..9c9b307c --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Albums.cs @@ -0,0 +1,23 @@ +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"; + public const string ADD_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks"; + } +} 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..dc7e6ed3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -0,0 +1,17 @@ +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 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/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpoint.cs new file mode 100644 index 00000000..c9805118 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpoint.cs @@ -0,0 +1,57 @@ +#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.AddAlbum; +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.AddAlbum; + +/// +/// API endpoint for the /{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..0fe02c37 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/AddAlbum/AddAlbumEndpointSummary.cs @@ -0,0 +1,779 @@ +#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", + "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..7dbd7949 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpoint.cs @@ -0,0 +1,53 @@ +#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.DeleteAlbum; +using Lumina.Contracts.Requests.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.DeleteAlbum; + +/// +/// API endpoint for the /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 containing the id of the album to be deleted. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteAlbumRequest request, CancellationToken cancellationToken) + { + Result result = await _deleteAlbumCommandHandler.HandleAsync(request.ToCommand(), 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..40645ebe --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/DeleteAlbum/DeleteAlbumEndpointSummary.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Albums.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 request, together with its tracks. 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."; + + ExampleRequest = new DeleteAlbumRequest( + ArtistId: Guid.NewGuid(), + AlbumId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to, taken from the route."); + RequestParam(r => r.AlbumId, "The Id of the album to delete, taken from the route. Required."); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..83d30a44 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpoint.cs @@ -0,0 +1,55 @@ +#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.GetAlbum; +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.GetAlbum; + +/// +/// API endpoint for the /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 containing the id of the album to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetAlbumRequest request, CancellationToken cancellationToken) + { + Result result = await _getAlbumQueryHandler.HandleAsync(request.ToQuery(), 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..3ff3cd62 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbum/GetAlbumEndpointSummary.cs @@ -0,0 +1,228 @@ +#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.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 request. 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."; + + ExampleRequest = new GetAlbumRequest( + ArtistId: Guid.NewGuid(), + AlbumId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to, taken from the route."); + RequestParam(r => r.AlbumId, "The Id of the album to get. 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(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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..96b95d67 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpoint.cs @@ -0,0 +1,56 @@ +#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.GetAlbumTracks; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Albums; +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 /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 request containing the id of the album whose tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetAlbumTracksRequest request, CancellationToken cancellationToken) + { + Result> result = await _getAlbumTracksQueryHandler.HandleAsync(request.ToQuery(), 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..515a12f0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracks/GetAlbumTracksEndpointSummary.cs @@ -0,0 +1,335 @@ +#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.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 request. 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."; + + ExampleRequest = new GetAlbumTracksRequest( + ArtistId: Guid.NewGuid(), + AlbumId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to, taken from the route."); + RequestParam(r => r.AlbumId, "The Id of the album whose tracks are retrieved, taken from the route. 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.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."); + 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."); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..6e9536dc --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpoint.cs @@ -0,0 +1,56 @@ +#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 /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 request containing the id of the album whose tracks are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetAlbumTracksLiteRequest request, CancellationToken cancellationToken) + { + Result> result = await _getAlbumTracksLiteQueryHandler.HandleAsync(request.ToQuery(), 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..b3c5ede8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/GetAlbumTracksLite/GetAlbumTracksLiteEndpointSummary.cs @@ -0,0 +1,144 @@ +#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( + ArtistId: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + CurrentPage: 1, + PerPage: 48 + ); + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to, taken from the route."); + RequestParam(r => r.AlbumId, "The Id of the album whose tracks are retrieved. Required."); + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/lite", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..13315100 --- /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 /{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..2cb70dc3 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Albums/UpdateAlbum/UpdateAlbumEndpointSummary.cs @@ -0,0 +1,388 @@ +#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 request, returning the full details of the updated album. The tracks of the album are left untouched. 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."; + + 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 + ) + ] + ); + + 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. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the album in English. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the album in English. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the album. Optional."); + 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."); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested 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 = "AlbumNotFound", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}", + 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", + "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..975ae4c2 --- /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 /{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..469b7036 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/AddArtist/AddArtistEndpointSummary.cs @@ -0,0 +1,917 @@ +#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].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.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.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, + 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") + ] + ) + ] + ) + ], + 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.", "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(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", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TracksListCannotBeNull", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "TrackPathMustBeWithinLibraryContentLocations", + "ArtistMustHaveAtLeastOneAlbum" + } + } + }, + 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..e8ba418d --- /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 /{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..9309f191 --- /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 request, 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..8ac49147 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpoint.cs @@ -0,0 +1,55 @@ +#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.GetArtist; +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.GetArtist; + +/// +/// API endpoint for the /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 containing the id of the artist to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistRequest request, CancellationToken cancellationToken) + { + Result result = await _getArtistQueryHandler.HandleAsync(request.ToQuery(), 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..dffb7881 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtist/GetArtistEndpointSummary.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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 request. 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."; + + ExampleRequest = new GetArtistRequest( + ArtistId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The Id of the artist to get. 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.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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}" + }, + 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/libraries/{libraryId}/artists/{artistId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}", + 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/{libraryId}/artists/{artistId}", + 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/{libraryId}/artists/{artistId}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..8ede1826 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpoint.cs @@ -0,0 +1,56 @@ +#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.GetArtistAlbums; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Artists; +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 /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 request containing the id of the artist whose albums are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistAlbumsRequest request, CancellationToken cancellationToken) + { + Result> result = await _getArtistAlbumsQueryHandler.HandleAsync(request.ToQuery(), 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..d4791ba5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbums/GetArtistAlbumsEndpointSummary.cs @@ -0,0 +1,302 @@ +#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.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 request, 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."; + + ExampleRequest = new GetArtistAlbumsRequest( + ArtistId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The Id of the artist whose albums are retrieved, taken from the route. 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(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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums" + }, + 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/libraries/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/albums", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..a88bedb9 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpoint.cs @@ -0,0 +1,56 @@ +#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 /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 request containing the id of the artist whose albums are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistAlbumsLiteRequest request, CancellationToken cancellationToken) + { + Result> result = await _getArtistAlbumsLiteQueryHandler.HandleAsync(request.ToQuery(), 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..79938165 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistAlbumsLite/GetArtistAlbumsLiteEndpointSummary.cs @@ -0,0 +1,139 @@ +#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( + ArtistId: Guid.NewGuid(), + CurrentPage: 1, + PerPage: 48 + ); + + RequestParam(r => r.ArtistId, "The Id of the artist whose albums are retrieved. Required."); + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/lite" + }, + 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/libraries/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/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/{libraryId}/artists/{artistId}/albums/lite", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..ff949b44 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpoint.cs @@ -0,0 +1,56 @@ +#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 /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 request containing the Id of the media library whose artists are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistsRequest request, CancellationToken cancellationToken) + { + Result> result = await _getArtistsQueryHandler.HandleAsync(request.ToQuery(), 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..f0273b51 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtists/GetArtistsEndpointSummary.cs @@ -0,0 +1,147 @@ +#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 request, 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( + LibraryId: Guid.NewGuid(), + CurrentPage: 1, + PerPage: 48, + SearchTerm: "queen" + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artists are retrieved. Required."); + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists" + }, + 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/libraries/{libraryId}/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/{libraryId}/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/{libraryId}/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/{libraryId}/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..a7b3a791 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpoint.cs @@ -0,0 +1,56 @@ +#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 /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 request containing the Id of the media library whose artists are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetArtistsLiteRequest request, CancellationToken cancellationToken) + { + Result> result = await _getArtistsLiteQueryHandler.HandleAsync(request.ToQuery(), 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..54a1e27a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/GetArtistsLite/GetArtistsLiteEndpointSummary.cs @@ -0,0 +1,126 @@ +#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( + LibraryId: Guid.NewGuid(), + CurrentPage: 1, + PerPage: 48, + SearchTerm: "queen" + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artists are retrieved. Required."); + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/lite" + }, + 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/libraries/{libraryId}/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/{libraryId}/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/{libraryId}/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/{libraryId}/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..5121a566 --- /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 /{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..765a8338 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Artists/UpdateArtist/UpdateArtistEndpointSummary.cs @@ -0,0 +1,903 @@ +#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.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 request, 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].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."); + + 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 AddAlbumRequest( + 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 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.", + 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 AddTrackRequest( + 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].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.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.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, + 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: 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, + 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 + ) + ], + Moods: + [ + new MoodDto(Name: "happy"), + new MoodDto(Name: "warm") + ], + Isrcs: + [ + new IsrcDto(Value: "GBUM71029609") + ] + ) + ] + ) + ], + 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, 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(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", + "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", + "RatingsListCannotBeNull", + "RatingValueMustBePositive", + "RatingValueCannotBeGreaterThanMaxValue", + "RatingMaxValueMustBePositive", + "RatingVoteCountMustBePositive", + "TracksListCannotBeNull", + "TrackPathCannotBeEmpty", + "TrackPathMustBeMaximum2048CharactersLong", + "TrackNumberMustBeGreaterThanZero", + "DiscNumberMustBeGreaterThanZero", + "ScriptMustBeMaximum50CharactersLong", + "UnknownMusicKey", + "BpmMustBeGreaterThanZero", + "WorkMustBeMaximum255CharactersLong", + "MoodNameCannotBeEmpty", + "IsrcValueCannotBeEmpty", + "ArtistMustHaveAtLeastOneAlbum" + } + } + }, + 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..03cc56c9 --- /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 /{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.Albums.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..1910e67e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/AddTrack/AddTrackEndpointSummary.cs @@ -0,0 +1,457 @@ +#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 = "Adds a new track to the album identified by the request, returning the full details of the newly created track. The track is added by an Admin, who can add tracks to the albums of all libraries, or by the owner of the library of the album the track is added to."; + + 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(), + 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") + ] + ); + + 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. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track. Optional."); + 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.Contributors, "The list of media contributors that performed on the track. Optional."); + RequestParam(r => r.Ratings, "The list of ratings for this track. Required."); + 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."); + + 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.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."); + 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."); + + 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, + 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") + ] + ) + ); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested 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 = "AlbumNotFound", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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/{libraryId}/artists/{artistId}/albums/{albumId}/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", + "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..4e265ba4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpoint.cs @@ -0,0 +1,53 @@ +#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.DeleteTrack; +using Lumina.Contracts.Requests.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.DeleteTrack; + +/// +/// API endpoint for the /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 containing the id of the track to be deleted. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(DeleteTrackRequest request, CancellationToken cancellationToken) + { + Result result = await _deleteTrackCommandHandler.HandleAsync(request.ToCommand(), 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..c5594cf4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/DeleteTrack/DeleteTrackEndpointSummary.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.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 request. 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."; + + ExampleRequest = new DeleteTrackRequest( + ArtistId: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + TrackId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album of the track belongs to, taken from the route."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to, taken from the route."); + RequestParam(r => r.TrackId, "The Id of the track to delete, taken from the route. Required."); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested track 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 = "TrackNotFound", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..0c1b6219 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrack; +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.GetTrack; + +/// +/// API endpoint for the /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 containing the id of the track to be retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetTrackRequest request, CancellationToken cancellationToken) + { + Result result = await _getTrackQueryHandler.HandleAsync(request.ToQuery(), 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..d90cd90b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrack/GetTrackEndpointSummary.cs @@ -0,0 +1,249 @@ +#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.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 request. 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."; + + ExampleRequest = new GetTrackRequest( + ArtistId: Guid.NewGuid(), + AlbumId: Guid.NewGuid(), + TrackId: Guid.NewGuid() + ); + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album of the track belongs to, taken from the route."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to, taken from the route."); + RequestParam(r => r.TrackId, "The Id of the track to get. 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.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."); + 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."); + + 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, + 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") + ] + ) + ); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested track 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 = "TrackNotFound", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "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..ddd441b2 --- /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 /{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..1f5c32c0 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/UpdateTrack/UpdateTrackEndpointSummary.cs @@ -0,0 +1,386 @@ +#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 request, returning the full details of the updated track. The media contributors of the track are left untouched. 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(), + 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") + ] + ); + + 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. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.Language!.LanguageName, "The full name of the language of the track in English. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.OriginalLanguage!.LanguageName, "The full name of the original language of the track in English. Optional."); + 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. Optional."); + RequestParam(r => r.Metadata!.Tags, "The list of tags that further describe or categorize the track. Optional."); + 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.Contributors, "The list of media contributors that performed on the track. Optional."); + RequestParam(r => r.Ratings, "The list of ratings for this track. Required."); + 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."); + + 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.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."); + 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."); + + 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, + 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") + ] + ) + ); + + 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 = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + }, + 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/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}" + } + } + ); + + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested track 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 = "TrackNotFound", + instance = "/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + 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/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty", + "TrackPathCannotBeEmpty", + "TrackNumberMustBeGreaterThanZero", + "MusicBrainzIdInvalidFormat" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs index 8d8b6b0c..4ee1c253 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpoint.cs @@ -48,7 +48,7 @@ public class AddBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken) { - // take unique identifiers from the route + // 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 bc0768c2..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,32 +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( - Path: "/media/libraries/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", @@ -70,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", @@ -212,17 +215,17 @@ public class AddBookEndpointSummary : Summary Response(201, "The new book is returned.", example: new BookResponse( - Id: Guid.NewGuid(), - LibraryId: Guid.NewGuid(), - Path: "/media/libraries/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" @@ -251,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", @@ -311,7 +311,6 @@ public class AddBookEndpointSummary : Summary ) ); - Response(401, "Authentication required.", "application/problem+json", example: new[] { 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..53a9598a 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 /{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..112cb5d7 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 /{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..67d1d533 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 /{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..35eb8747 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 /{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 5b3a83e8..37dbfdb4 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 @@ -48,7 +48,7 @@ public class UpdateBookEndpoint : BaseEndpoint /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdateBookRequest request, CancellationToken cancellationToken) { - // take unique identifiers from the route + // 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); 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 0c478ada..9cd8830c 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,8 +27,8 @@ 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 request. The request is handled by an Admin, who can update the books of all libraries, or by the owner of the library."; RequestParam(r => r.Metadata, "The written content metadata of the book. Required."); RequestParam(r => r.Metadata!.Title, "The title of the book. Required."); @@ -258,9 +258,7 @@ public class UpdateBookEndpointSummary : Summary -/// API endpoint for the /books/{id}/cover route. +/// API endpoint for the /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..1edda946 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 @@ -21,17 +23,38 @@ public class UpdateBookCoverEndpointSummary : Summary { { "General.Validation", new[] { + "LibraryIdCannotBeEmpty", "BookIdCannotBeEmpty", "BookCoverCannotBeNull", + "FileNameCannotBeEmpty", "FileTooLarge", "CoverFileMustBeAnImage" } 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/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/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/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..451067d7 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 @@ -21,10 +21,12 @@ 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..88b77f2a 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 @@ -23,10 +23,12 @@ 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/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/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..0c51beb8 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 @@ -21,9 +21,11 @@ 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/UpdateBookCover/UpdateBookCoverEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs index d6a5ee7b..10993e66 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookCover/UpdateBookCoverEndpoint.cs @@ -1,6 +1,7 @@ #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.Common; using Microsoft.AspNetCore.Builder; @@ -15,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.UpdateBookCover; /// -/// 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/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/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/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/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/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/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.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.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/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/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs similarity index 91% rename from tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs rename to tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs index 21a94f20..a6f0ff83 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -1,7 +1,7 @@ #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.Repositories.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -16,7 +16,7 @@ using System.Threading; using System.Threading.Tasks; #endregion -namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Books; +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.BookLibrary; /// /// Contains integration tests for the class, exercising it against a real SQLite database. @@ -43,12 +43,12 @@ public class BookRepositoryTests 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)]; + 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.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; + unchangedBook.Artwork = [_bookArtworkEntityFixture.Create(bookId: unchangedBook.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; context.Books.AddRange(changedBook, unchangedBook); await context.SaveChangesAsync(); @@ -58,10 +58,10 @@ public class BookRepositoryTests // 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); + 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.BookArtwork.Single().Status); + 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); @@ -116,10 +116,10 @@ public class BookRepositoryTests 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)]; + book.Artwork = [_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)]; + bookOfAnotherLibrary.Artwork = [_bookArtworkEntityFixture.Create(bookId: bookOfAnotherLibrary.Id, artworkType: ArtworkType.Cover, ordinal: 0, status: ArtworkStatus.Enriched)]; context.Books.AddRange(book, bookOfAnotherLibrary); await context.SaveChangesAsync(); 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/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 2e775cfa..c26b1b1e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -11,14 +11,13 @@ 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.Common.Errors; -using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Common; using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Presentation.Api.IntegrationTests.Common.Converters; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; @@ -33,6 +32,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 @@ -48,12 +48,8 @@ public class AddBookEndpointTests : IClassFixture private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { - ReferenceHandler = ReferenceHandler.Preserve, PropertyNameCaseInsensitive = true, - Converters = { - new JsonStringEnumConverter(JsonNamingPolicy.CamelCase), - new BookJsonConverter() - } + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } }; private readonly AddBookRequestFixture _requestBookFixture = new(); private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); @@ -106,62 +102,62 @@ public class AddBookEndpointTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); - Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + BookResponse? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(bookResponse); // metadata checks Assert.Equal(bookRequest.Metadata!.Title, bookResponse!.Metadata.Title); - Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle.Value); - Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description.Value); - Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher.Value); - Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount.Value); + Assert.Equal(bookRequest.Metadata.OriginalTitle, bookResponse.Metadata.OriginalTitle); + Assert.Equal(bookRequest.Metadata.Description, bookResponse.Metadata.Description); + Assert.Equal(bookRequest.Metadata.Publisher, bookResponse.Metadata.Publisher); + Assert.Equal(bookRequest.Metadata.PageCount, bookResponse.Metadata.PageCount); - Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo.OriginalReleaseDate.Value); - Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear.Value); - Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate.Value); - Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear.Value); - Assert.Equal(bookRequest.Metadata.ReleaseInfo!.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry.Value); - Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion.Value); + Assert.Equal(bookRequest.Metadata.ReleaseInfo!.OriginalReleaseDate, bookResponse.Metadata.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(bookRequest.Metadata.ReleaseInfo.OriginalReleaseYear, bookResponse.Metadata.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseDate, bookResponse.Metadata.ReleaseInfo.ReReleaseDate); + Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReReleaseYear, bookResponse.Metadata.ReleaseInfo.ReReleaseYear); + Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseCountry, bookResponse.Metadata.ReleaseInfo.ReleaseCountry); + Assert.Equal(bookRequest.Metadata.ReleaseInfo.ReleaseVersion, bookResponse.Metadata.ReleaseInfo.ReleaseVersion); // language checks - Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language.Value.LanguageCode); - Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.Value.LanguageName); - Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.Value.NativeName.Value); + Assert.Equal(bookRequest.Metadata.Language!.LanguageCode, bookResponse.Metadata.Language!.LanguageCode); + Assert.Equal(bookRequest.Metadata.Language.LanguageName, bookResponse.Metadata.Language.LanguageName); + Assert.Equal(bookRequest.Metadata.Language.NativeName, bookResponse.Metadata.Language.NativeName); // original language checks - Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage.Value.LanguageCode); - Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.Value.LanguageName); - Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.Value.NativeName.Value); + Assert.Equal(bookRequest.Metadata.OriginalLanguage!.LanguageCode, bookResponse.Metadata.OriginalLanguage!.LanguageCode); + Assert.Equal(bookRequest.Metadata.OriginalLanguage.LanguageName, bookResponse.Metadata.OriginalLanguage.LanguageName); + Assert.Equal(bookRequest.Metadata.OriginalLanguage.NativeName, bookResponse.Metadata.OriginalLanguage.NativeName); // genres checks - Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres.Count); + Assert.Equal(bookRequest.Metadata.Genres!.Count, bookResponse.Metadata.Genres!.Count); Assert.Equal( bookRequest.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x), bookResponse.Metadata.Genres.Select(genre => genre.Name).OrderBy(x => x)); // tags checks - Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags.Count); + Assert.Equal(bookRequest.Metadata.Tags!.Count, bookResponse.Metadata.Tags!.Count); Assert.Equal( bookRequest.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x), bookResponse.Metadata.Tags.Select(tag => tag.Name).OrderBy(x => x)); // book specific properties - Assert.Equal(bookRequest.Format, bookResponse.Format.Value); - Assert.Equal(bookRequest.Edition, bookResponse.Edition.Value); - Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber.Value); - Assert.Equal(bookRequest.ASIN, bookResponse.ASIN.Value); - Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId.Value); - Assert.Equal(bookRequest.LCCN, bookResponse.LCCN.Value); - Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber.Value); - Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId.Value); - Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId.Value); - Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId.Value); - Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId.Value); - Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId.Value); + Assert.Equal(bookRequest.Format, bookResponse.Format); + Assert.Equal(bookRequest.Edition, bookResponse.Edition); + Assert.Equal(bookRequest.VolumeNumber, bookResponse.VolumeNumber); + Assert.Equal(bookRequest.ASIN, bookResponse.ASIN); + Assert.Equal(bookRequest.GoodreadsId, bookResponse.GoodreadsId); + Assert.Equal(bookRequest.LCCN, bookResponse.LCCN); + Assert.Equal(bookRequest.OCLCNumber, bookResponse.OCLCNumber); + Assert.Equal(bookRequest.OpenLibraryId, bookResponse.OpenLibraryId); + Assert.Equal(bookRequest.LibraryThingId, bookResponse.LibraryThingId); + Assert.Equal(bookRequest.GoogleBooksId, bookResponse.GoogleBooksId); + Assert.Equal(bookRequest.BarnesAndNobleId, bookResponse.BarnesAndNobleId); + Assert.Equal(bookRequest.AppleBooksId, bookResponse.AppleBooksId); // ISBNs checks - Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs.Count); + Assert.Equal(bookRequest.ISBNs!.Count, bookResponse.ISBNs!.Count); var requestIsbnData = bookRequest.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList(); var responseIsbnData = bookResponse.ISBNs.Select(isbn => new { isbn.Value, isbn.Format }).OrderBy(x => x.Value).ToList(); Assert.Equal(requestIsbnData.Count, responseIsbnData.Count); @@ -172,9 +168,9 @@ public class AddBookEndpointTests : IClassFixture } // ratings checks - Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings.Count); + Assert.Equal(bookRequest.Ratings!.Count, bookResponse.Ratings!.Count); var requestRatingData = bookRequest.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList(); - var responseRatingData = bookResponse.Ratings.Select(r => new { Source = r.Source.Value, r.Value, r.MaxValue, VoteCount = r.VoteCount.Value }).OrderBy(x => x.Source).ToList(); + var responseRatingData = bookResponse.Ratings.Select(r => new { r.Source, r.Value, r.MaxValue, r.VoteCount }).OrderBy(x => x.Source).ToList(); Assert.Equal(requestRatingData.Count, responseRatingData.Count); for (int i = 0; i < requestRatingData.Count; i++) { @@ -186,18 +182,18 @@ public class AddBookEndpointTests : IClassFixture // series checks if (bookRequest.Series is not null) - Assert.Equal(bookRequest.Series.Title, bookResponse.Series.Value.Metadata.Title); + Assert.Equal(bookRequest.Series.Title, bookResponse.Series!.Title); else - Assert.Null(bookResponse.Series.Value); + Assert.Null(bookResponse.Series); // check Location header Assert.NotNull(response.Headers.Location); string locationUri = response.Headers.Location!.ToString(); - Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id.Value}", locationUri); + Assert.EndsWith($"/api/v1/libraries/{_libraryId}/books/{bookResponse.Id}", locationUri); // extract ID from Location header and compare string idFromHeader = locationUri.Split('/').Last(); - Assert.Equal(idFromHeader, bookResponse!.Id.ToString()); + Assert.Equal(idFromHeader, bookResponse.Id.ToString()); } [Fact] @@ -1119,7 +1115,7 @@ public class AddBookEndpointTests : IClassFixture HttpResponseMessage response = await PostBookAsync(bookRequest); // Assert - await AssertUnprocessableEntityWithValidationErrors(response, Errors.WrittenContent.ContributorsListCannotBeNull.Description); + await AssertUnprocessableEntityWithValidationErrors(response, Errors.MediaContributor.ContributorsListCannotBeNull.Description); } [Fact] @@ -1235,15 +1231,15 @@ public class AddBookEndpointTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); Assert.Equal(HttpStatusCode.Created, response.StatusCode); - Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + BookResponse? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); Assert.NotNull(bookResponse); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); List links = [.. dbContext.Books - .Include(book => book.BookContributors) - .Single(book => book.Id == bookResponse!.Id.Value) - .BookContributors]; + .Include(book => book.Contributors) + .Single(book => book.Id == bookResponse!.Id) + .Contributors]; Assert.Equal(2, links.Count); Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId)); Assert.Contains(links, link => link.Role == MediaContributorRole.Author); @@ -1754,6 +1750,51 @@ public class AddBookEndpointTests : IClassFixture Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase); } + [Fact] + public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + Guid libraryId = Guid.NewGuid(); + AddBookRequest request = _requestBookFixture.Create(contributors: []); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/books", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task AddBook_WhenCalledWithCancellationToken_ShouldCompleteSuccessfully() + { + // Arrange + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []); + using CancellationTokenSource cts = new(TimeSpan.FromSeconds(5)); + + // Act & Assert + Exception? exception = await Record.ExceptionAsync(async () => + await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token) + ); + Assert.Null(exception); + } + + [Fact] + public async Task AddBook_WhenCancellationTokenIsCanceled_ShouldThrowTaskCanceledException() + { + // Arrange + AddBookRequest bookRequest = _requestBookFixture.Create(contributors: []); + using CancellationTokenSource cts = new(); + + // Act & Assert + Exception? exception = await Record.ExceptionAsync(async () => + { + cts.Cancel(); + await _client.PostAsJsonAsync($"/api/v1/libraries/{_libraryId}/books", bookRequest, cts.Token); + }); + Assert.IsType(exception); + } + /// /// Posts a request to add a book to the media library owned by the authenticated user of the current test. /// @@ -1821,7 +1862,7 @@ public class AddBookEndpointTests : IClassFixture { HttpResponseMessage response = await PostBookAsync(bookRequest); response.EnsureSuccessStatusCode(); - Book? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + BookResponse? bookResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); Assert.Equal(HttpStatusCode.Created, response.StatusCode); Assert.NotNull(bookResponse); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs index 82e937fb..44190a99 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingAvailability/GetReadingAvailabilityEndpointTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentL 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.Reading; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -36,6 +37,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -63,7 +65,7 @@ public class GetReadingAvailabilityEndpointTests : IClassFixture + /// Seeds a user that is not the authenticated one and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + /// /// Gets the Id of the currently authenticated test user. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs index 7fb86434..5ab28583 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Reading/GetReadingManifest/GetReadingManifestEndpointTests.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 GetReadingManifestEndpointTests : 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 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 cdd64907..93692ab9 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,4 +1,4 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; @@ -35,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 @@ -134,9 +135,9 @@ public class UpdateBookEndpointTests : IClassFixture(); List links = dbContext.Books - .Include(book => book.BookContributors) + .Include(book => book.Contributors) .Single(book => book.Id == bookId) - .BookContributors + .Contributors .ToList(); Assert.Equal(2, links.Count); Assert.All(links, link => Assert.Equal(contributorId, link.MediaContributorId)); @@ -1792,6 +1793,40 @@ 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. /// 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 _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/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/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 4f5a2c8d..f6ff61d3 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 @@ -50,7 +50,7 @@ public class AddBookEndpointTests : IClassFixture, IDisposable } [Fact] - public async Task AddBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + public async Task AddBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange Guid libraryId = Guid.NewGuid(); 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..522214e3 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,59 @@ 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("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..8436f711 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,59 @@ 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("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..d4e944b6 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,55 @@ 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("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..adc0dd91 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,55 @@ 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("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 18cbfadb..a7c147a9 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 @@ -40,7 +40,7 @@ public class UpdateBookEndpointTests : IClassFixture } [Fact] - public async Task UpdateBook_WhenCalledWithoutAuthentication_ShouldReturnUnauthorized() + public async Task UpdateBook_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange HttpClient client = _apiFactory.CreateClient(); 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..21c54651 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,62 @@ 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("NotAuthorized", problemDetails["detail"].GetString()); + + await _apiFactory.RemoveTestUserAsync(ownerUsername); + await _apiFactory.RemoveTestUserAsync(requesterUsername); } [Theory] @@ -57,7 +105,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 +129,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.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/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/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/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/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/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/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index ca910c46..c795635f 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 @@ -1,10 +1,10 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== 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; @@ -321,9 +321,9 @@ public class AddBookCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.NotNull(insertedEntity); - Assert.Equal(2, insertedEntity!.BookContributors.Count); - Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == firstContributorId && contributor.Role == MediaContributorRole.Author); - Assert.Contains(insertedEntity.BookContributors, contributor => contributor.MediaContributorId == secondContributorId && contributor.Role == MediaContributorRole.Illustrator); + 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()); } @@ -355,10 +355,10 @@ public class AddBookCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.NotNull(insertedEntity); - Assert.Equal(2, insertedEntity!.BookContributors.Count); - Assert.All(insertedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId)); - Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author); - Assert.Contains(insertedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.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()); } 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 9427cb07..6f2c0b09 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 @@ -1545,7 +1545,7 @@ public class AddBookCommandValidatorTests List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] @@ -1558,7 +1558,7 @@ public class AddBookCommandValidatorTests List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] 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 71f14199..365ad36a 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 ===================================================================================== +#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,6 +12,7 @@ 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; @@ -42,6 +45,7 @@ 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; @@ -57,6 +61,7 @@ public class UpdateBookCommandHandlerTests 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. @@ -64,10 +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(); @@ -82,6 +89,9 @@ public class UpdateBookCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([]); _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 => @@ -268,10 +278,10 @@ public class UpdateBookCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.NotNull(updatedEntity); - Assert.Equal(2, updatedEntity!.BookContributors.Count); - Assert.All(updatedEntity.BookContributors, linkedContributor => Assert.Equal(contributorId, linkedContributor.MediaContributorId)); - Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.Author); - Assert.Contains(updatedEntity.BookContributors, linkedContributor => linkedContributor.Role == MediaContributorRole.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()); } @@ -304,54 +314,12 @@ public class UpdateBookCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.NotNull(updatedEntity); - Assert.Equal(2, updatedEntity!.BookContributors.Count); - Assert.Equal(firstContributorId, updatedEntity.BookContributors[0].MediaContributorId); - Assert.Equal(secondContributorId, 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() - { - // Arrange - UpdateBookCommand command = _commandBookFixture.Create(); - BookEntity existingBook = _bookEntityFixture.Create(id: Guid.Parse(command.BookId!), libraryId: Guid.Parse(command.LibraryId!)); - 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 - }); - 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(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); - } - [Fact] public async Task HandleAsync_WhenCalledWithInvalidIsbn_ShouldReturnFailureResult() { @@ -492,4 +460,25 @@ public class UpdateBookCommandHandlerTests 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 fb904660..519307e6 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 @@ -1532,7 +1532,7 @@ public class UpdateBookCommandValidatorTests List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull); + result.ShouldHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] @@ -1545,7 +1545,7 @@ public class UpdateBookCommandValidatorTests List result = _validator.TestValidate(bookCommand); // Assert - result.ShouldNotHaveValidationError(Errors.WrittenContent.ContributorsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.MediaContributor.ContributorsListCannotBeNull); } [Fact] 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 7ecf1e42..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,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.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; @@ -94,7 +94,7 @@ public class GetBookQueryHandlerTests Guid bookId = Guid.Parse(query.BookId!); BookEntity bookEntity = _bookEntityFixture.Create(id: bookId, libraryId: libraryId); Guid contributorId = Guid.NewGuid(); - bookEntity.BookContributors = + bookEntity.Contributors = [ _bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId, role: MediaContributorRole.Author) ]; 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 463e367f..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; 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 a495b3e3..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,5 +1,5 @@ #region ========================================================================= USING ===================================================================================== -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; 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/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/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.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs index b6f29943..8909d0d8 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs @@ -55,7 +55,7 @@ public class BookMetadataDtoTests "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 MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), MediaContributorRole.Author)], [new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)], "https://example.com/dune.jpg" ); 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/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseTests.cs new file mode 100644 index 00000000..55e45705 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/UpdateBookCoverResponseTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +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 UpdateBookCoverResponseTests +{ + private readonly UpdateBookCoverResponseFixture _updateBookCoverResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUpdateBookCoverResponse_ShouldPreserveValues() + { + // Arrange + UpdateBookCoverResponse expected = _updateBookCoverResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateBookCoverResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + UpdateBookCoverResponse sut = _updateBookCoverResponseFixture.Create(); + + // Act + sut.Deconstruct(out string coverPath); + + // Assert + Assert.Equal(sut.CoverPath, coverPath); + } +} 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 95% 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 23b3f9e7..c4375abc 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/BookLibrary/BookRepositoryTests.cs @@ -11,7 +11,7 @@ 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; @@ -29,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. @@ -441,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); @@ -455,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() { @@ -498,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, role: MediaContributorRole.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(), role: MediaContributorRole.Illustrator)]; + data.Contributors = [_bookContributorEntityFixture.Create(bookId: storedBook.Id, mediaContributorId: Guid.NewGuid(), role: MediaContributorRole.Illustrator)]; // Act Result result = await _sut.UpdateAsync(data, CancellationToken.None); @@ -516,12 +543,12 @@ 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(MediaContributorRole.Illustrator, retrievedContributor.Role); @@ -724,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(); @@ -756,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(); @@ -813,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); @@ -827,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); @@ -869,7 +896,7 @@ 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(); @@ -882,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] @@ -1320,7 +1347,7 @@ public class BookRepositoryTests Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); book.LibraryId = libraryId; - book.BookArtwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")]; + book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, fileName: "cover.jpg")]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); @@ -1342,7 +1369,7 @@ public class BookRepositoryTests Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); book.LibraryId = libraryId; - book.BookArtwork = []; + book.Artwork = []; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); 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 96% 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..671ba1af 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. 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..28cce970 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] @@ -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.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/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.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.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/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 0dc64bef..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; @@ -49,7 +50,7 @@ public class AddBookEndpointTests BookResponse expectedResponse = _bookResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); - ConfigureRequest(libraryId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -86,7 +87,7 @@ public class AddBookEndpointTests } [Fact] - public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendAddBookCommandToSender() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -94,7 +95,7 @@ public class AddBookEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(libraryId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -142,10 +143,10 @@ public class AddBookEndpointTests Guid libraryId = Guid.NewGuid(); AddBookRequest request = _addBookRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - Error validationError = Error.Validation(description: "LibraryIdCannotBeEmpty"); + Error validationError = Errors.Library.LibraryIdCannotBeEmpty; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(validationError); - ConfigureRequest(libraryId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -157,6 +158,7 @@ public class AddBookEndpointTests 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"]); @@ -170,7 +172,7 @@ public class AddBookEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest("not-a-library-guid"); + _sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid"; // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -189,7 +191,7 @@ public class AddBookEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequestWithoutLibraryId(); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -199,21 +201,4 @@ public class AddBookEndpointTests Arg.Is(command => command.LibraryId == null), Arg.Is(cancellationToken)); } - - /// - /// Sets the libraryId route value the endpoint reads the identifier from. - /// - /// The raw route value of the library Id. - private void ConfigureRequest(string libraryId) - { - _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId; - } - - /// - /// Leaves the libraryId route value unset. - /// - private void ConfigureRequestWithoutLibraryId() - { - _sut.HttpContext.Request.RouteValues.Remove("libraryId"); - } } 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 666ce786..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; @@ -49,7 +50,8 @@ public class UpdateBookEndpointTests BookResponse expectedResponse = _bookResponseFixture.Create(); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); - ConfigureRequest(libraryId.ToString(), routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -70,7 +72,8 @@ public class UpdateBookEndpointTests Error expectedError = Error.NotFound("Book.NotFound", "BookNotFound"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedError); - ConfigureRequest(libraryId.ToString(), routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -94,10 +97,11 @@ public class UpdateBookEndpointTests Guid routeId = Guid.NewGuid(); 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(libraryId.ToString(), routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act IResult result = await _sut.ExecuteAsync(request, cancellationToken); @@ -109,13 +113,14 @@ 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_WhenCalled_ShouldSendUpdateBookCommandToHandler() + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateBookCommandToSender() { // Arrange Guid libraryId = Guid.NewGuid(); @@ -124,7 +129,8 @@ public class UpdateBookEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest(libraryId.ToString(), routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -152,7 +158,8 @@ public class UpdateBookEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequest("not-a-library-guid", "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); @@ -171,7 +178,8 @@ public class UpdateBookEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(_bookResponseFixture.Create())); - ConfigureRequestWithoutIds(); + _sut.HttpContext.Request.RouteValues.Remove("libraryId"); + _sut.HttpContext.Request.RouteValues.Remove("bookId"); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -201,7 +209,8 @@ public class UpdateBookEndpointTests callInfo.Arg().ThrowIfCancellationRequested(); return Result.From(_bookResponseFixture.Create()); }, callInfo.Arg())); - ConfigureRequest(libraryId.ToString(), routeId.ToString()); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString(); + _sut.HttpContext.Request.RouteValues["bookId"] = routeId.ToString(); // Act Task operationTask = _sut.ExecuteAsync(request, cts.Token); @@ -212,24 +221,4 @@ public class UpdateBookEndpointTests // Assert await Assert.ThrowsAnyAsync(() => operationTask); } - - /// - /// Sets the libraryId and id route values the endpoint reads the identifiers from. - /// - /// The raw route value of the library Id. - /// The raw route value of the book Id. - private void ConfigureRequest(string libraryId, string bookId) - { - _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId; - _sut.HttpContext.Request.RouteValues["bookId"] = bookId; - } - - /// - /// Leaves the libraryId and id route values unset. - /// - private void ConfigureRequestWithoutIds() - { - _sut.HttpContext.Request.RouteValues.Remove("libraryId"); - _sut.HttpContext.Request.RouteValues.Remove("bookId"); - } } 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/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/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.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/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}