From 9889c86c760970282a9baaa1fcbc3560116550d8 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 21 Oct 2026 16:30:58 +0300 Subject: [PATCH] Adds playlist management and playback --- docs/manual/index.md | 2 +- docs/manual/using-lumina/index.md | 17 +- .../architecture-decision-record-0006.md | 26 +- .../architecture-decision-record-0014.md | 14 + docs/technical/domain/UbiquitousLanguage.md | 9 +- docs/technical/theming/Theming.md | 73 +- .../MusicLibrary/Albums/AlbumLiteRow.cs | 46 +- .../MusicLibrary/Artists/ArtistLiteRow.cs | 25 +- .../MusicLibrary/Tracks/ShuffleTrackRowDto.cs | 53 +- .../Tracks/TrackAccessSummaryDto.cs | 18 + .../MusicLibrary/Tracks/TrackLiteRow.cs | 39 +- .../BookLibrary/BookLiteRow.cs | 32 +- .../DTO/Playlists/PlaylistBulkAddResultDto.cs | 16 + .../DTO/Playlists/PlaylistDetailsDto.cs | 16 + .../DTO/Playlists/PlaylistEntryDisplayDto.cs | 29 + .../Common/DTO/Playlists/PlaylistEntryDto.cs | 17 + .../DTO/Playlists/PlaylistSummaryDto.cs | 26 + .../Entities/Playlists/PlaylistEntity.cs | 80 + .../Entities/Playlists/PlaylistEntryEntity.cs | 64 + .../MusicLibrary/ITrackRepository.cs | 8 + .../Playlists/IPlaylistRepository.cs | 129 + .../Common/DataAccess/UoW/IUnitOfWork.cs | 6 + .../AddPlaylistEntriesRequestMapping.cs | 23 + .../AddPlaylistEntryRequestMapping.cs | 23 + .../AddPlaylistScopeEntriesRequestMapping.cs | 23 + .../Playlists/CreatePlaylistRequestMapping.cs | 22 + .../MovePlaylistEntryRequestMapping.cs | 24 + .../Playlists/PlaylistDetailsDtoMapping.cs | 31 + .../Playlists/PlaylistEntityMapping.cs | 49 + .../Playlists/PlaylistEntryDtoMapping.cs | 51 + .../Playlists/PlaylistEntryEntityMapping.cs | 31 + .../Mapping/Playlists/PlaylistEntryMapping.cs | 31 + .../Mapping/Playlists/PlaylistMapping.cs | 40 + .../Playlists/PlaylistSummaryDtoMapping.cs | 29 + .../Playlists/UpdatePlaylistRequestMapping.cs | 23 + .../AddPlaylistEntriesCommand.cs | 19 + .../AddPlaylistEntriesCommandHandler.cs | 120 + .../AddPlaylistEntriesCommandValidator.cs | 42 + .../AddPlaylistEntryCommand.cs | 18 + .../AddPlaylistEntryCommandHandler.cs | 124 + .../AddPlaylistEntryCommandValidator.cs | 38 + .../AddPlaylistScopeEntriesCommand.cs | 22 + .../AddPlaylistScopeEntriesCommandHandler.cs | 107 + ...AddPlaylistScopeEntriesCommandValidator.cs | 41 + .../CreatePlaylist/CreatePlaylistCommand.cs | 20 + .../CreatePlaylistCommandHandler.cs | 105 + .../CreatePlaylistCommandValidator.cs | 40 + .../DeletePlaylist/DeletePlaylistCommand.cs | 15 + .../DeletePlaylistCommandHandler.cs | 102 + .../DeletePlaylistCommandValidator.cs | 29 + .../MovePlaylistEntryCommand.cs | 20 + .../MovePlaylistEntryCommandHandler.cs | 80 + .../MovePlaylistEntryCommandValidator.cs | 47 + .../RemovePlaylistEntryCommand.cs | 17 + .../RemovePlaylistEntryCommandHandler.cs | 78 + .../RemovePlaylistEntryCommandValidator.cs | 38 + .../UpdatePlaylist/UpdatePlaylistCommand.cs | 19 + .../UpdatePlaylistCommandHandler.cs | 112 + .../UpdatePlaylistCommandValidator.cs | 41 + .../Queries/GetPlaylist/GetPlaylistQuery.cs | 19 + .../GetPlaylist/GetPlaylistQueryHandler.cs | 110 + .../GetPlaylist/GetPlaylistQueryValidator.cs | 37 + .../Queries/GetPlaylist/PlaylistWindow.cs | 17 + .../Queries/GetPlaylists/GetPlaylistsQuery.cs | 10 + .../GetPlaylists/GetPlaylistsQueryHandler.cs | 60 + .../Playlists/AddPlaylistEntriesRequest.cs | 16 + .../Playlists/AddPlaylistEntryRequest.cs | 15 + .../AddPlaylistScopeEntriesRequest.cs | 19 + .../Playlists/CreatePlaylistRequest.cs | 19 + .../Requests/Playlists/GetPlaylistRequest.cs | 16 + .../Playlists/MovePlaylistEntryRequest.cs | 14 + .../Playlists/UpdatePlaylistRequest.cs | 16 + .../Playlists/PlaylistDetailsResponse.cs | 24 + .../Playlists/PlaylistEntriesAddedResponse.cs | 19 + .../Playlists/PlaylistEntryAddedResponse.cs | 19 + .../Playlists/PlaylistEntryMovedResponse.cs | 21 + .../Playlists/PlaylistEntryRemovedResponse.cs | 21 + .../Playlists/PlaylistEntryResponse.cs | 38 + .../Responses/Playlists/PlaylistResponse.cs | 31 + .../Playlists/PlaylistSummaryResponse.cs | 28 + .../Configuration/PlaylistConfiguration.cs | 92 + .../PlaylistEntryConfiguration.cs | 70 + .../Common/Dapper/SqliteGuidTypeHandler.cs | 11 +- .../20261021090430_AddsPlaylists.Designer.cs | 3673 +++++++++++++++++ .../20261021090430_AddsPlaylists.cs | 93 + .../LuminaDbContextModelSnapshot.cs | 136 + .../Persistence/CollectionReconciler.cs | 13 +- .../Persistence/EditableValuesCopier.cs | 8 +- .../BookLibrary/BookRepository.cs | 14 +- .../LibraryScanSnapshotRepository.cs | 2 +- .../MusicLibrary/AlbumRepository.cs | 22 +- .../MusicLibrary/ArtistRepository.cs | 14 +- .../MusicLibrary/TrackRepository.cs | 87 +- .../Playlists/PlaylistRepository.cs | 1018 +++++ .../Core/UoW/LuminaDbContext.cs | 3 + src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 15 + .../Enums/Playlists/PlaylistMediaItemType.cs | 22 + .../Common/Enums/Playlists/PlaylistType.cs | 17 + .../Common/Errors/Errors.Playlist.cs | 29 + .../MediaItemAggregate/MediaItemId.cs | 54 + .../UserAggregate/UserId.cs | 51 + .../Entities/PlaylistEntry.cs | 62 + .../Events/PlaylistCreatedDomainEvent.cs | 29 + .../Events/PlaylistDeletedDomainEvent.cs | 24 + .../PlaylistDetailsUpdatedDomainEvent.cs | 26 + .../PlaylistAggregate/Playlist.cs | 228 + .../ValueObjects/PlaylistEntryId.cs | 51 + .../ValueObjects/PlaylistId.cs | 51 + .../UserAggregate/UserId.cs | 2 +- .../LibraryOwnershipPolicy.cs | 36 +- .../EventualConsistencyMiddleware.cs | 49 +- .../ExceptionHandlingMiddleware.cs | 8 +- .../Routes/Playlists/ApiRoutes.Playlists.cs | 24 + .../AddPlaylistEntriesEndpoint.cs | 59 + .../AddPlaylistEntriesEndpointSummary.cs | 159 + .../AddPlaylistEntryEndpoint.cs | 59 + .../AddPlaylistEntryEndpointSummary.cs | 181 + .../AddPlaylistScopeEntriesEndpoint.cs | 59 + .../AddPlaylistScopeEntriesEndpointSummary.cs | 149 + .../CreatePlaylist/CreatePlaylistEndpoint.cs | 57 + .../CreatePlaylistEndpointSummary.cs | 136 + .../DeletePlaylist/DeletePlaylistEndpoint.cs | 56 + .../DeletePlaylistEndpointSummary.cs | 95 + .../GetPlaylist/GetPlaylistEndpoint.cs | 68 + .../GetPlaylist/GetPlaylistEndpointSummary.cs | 136 + .../GetPlaylists/GetPlaylistsEndpoint.cs | 59 + .../GetPlaylistsEndpointSummary.cs | 78 + .../MovePlaylistEntryEndpoint.cs | 60 + .../MovePlaylistEntryEndpointSummary.cs | 146 + .../RemovePlaylistEntryEndpoint.cs | 58 + .../RemovePlaylistEntryEndpointSummary.cs | 127 + .../UpdatePlaylist/UpdatePlaylistEndpoint.cs | 60 + .../UpdatePlaylistEndpointSummary.cs | 128 + .../Core/Themes/Bundled/editorial-paper.zip | Bin 377850 -> 379844 bytes .../Core/Themes/Bundled/lumina-default.zip | Bin 377313 -> 379307 bytes .../DTO/Playlists/PlaylistDetailsDto.cs | 24 + .../Common/DTO/Playlists/PlaylistDto.cs | 31 + .../DTO/Playlists/PlaylistEntriesAddedDto.cs | 19 + .../DTO/Playlists/PlaylistEntryAddedDto.cs | 19 + .../Common/DTO/Playlists/PlaylistEntryDto.cs | 38 + .../DTO/Playlists/PlaylistEntryMovedDto.cs | 21 + .../DTO/Playlists/PlaylistSummaryDto.cs | 28 + .../Enums/Playlists/PlaylistMediaItemType.cs | 22 + .../Common/Enums/Playlists/PlaylistType.cs | 17 + .../Playlists/AddPlaylistEntriesRequest.cs | 16 + .../Playlists/AddPlaylistEntryRequest.cs | 15 + .../AddPlaylistScopeEntriesRequest.cs | 19 + .../Playlists/CreatePlaylistRequest.cs | 19 + .../Requests/Playlists/GetPlaylistRequest.cs | 16 + .../Playlists/MovePlaylistEntryRequest.cs | 14 + .../Playlists/UpdatePlaylistRequest.cs | 16 + .../Common/Routes/ApiRoutes.Playlists.cs | 24 + .../Common/Routes/WebRoutes.Playlists.cs | 27 + .../AddPlaylistEntriesEndpoint.cs | 60 + .../AddPlaylistEntriesEndpointSummary.cs | 41 + .../AddPlaylistEntryEndpoint.cs | 60 + .../AddPlaylistEntryEndpointSummary.cs | 37 + .../AddPlaylistScopeEntriesEndpoint.cs | 60 + .../AddPlaylistScopeEntriesEndpointSummary.cs | 41 + .../CreatePlaylist/CreatePlaylistEndpoint.cs | 55 + .../CreatePlaylistEndpointSummary.cs | 39 + .../DeletePlaylist/DeletePlaylistEndpoint.cs | 57 + .../DeletePlaylistEndpointSummary.cs | 29 + .../GetPlaylist/GetPlaylistEndpoint.cs | 69 + .../GetPlaylist/GetPlaylistEndpointSummary.cs | 38 + .../GetPlaylists/GetPlaylistsEndpoint.cs | 55 + .../GetPlaylistsEndpointSummary.cs | 28 + .../Index/PlaylistsIndexViewEndpoint.cs | 100 + .../PlaylistsIndexViewEndpointSummary.cs | 24 + .../Playlists/Item/AddPlaylistViewEndpoint.cs | 126 + .../Item/AddPlaylistViewEndpointSummary.cs | 24 + .../Item/PlaylistItemViewEndpoint.cs | 135 + .../Item/PlaylistItemViewEndpointSummary.cs | 26 + .../MovePlaylistEntryEndpoint.cs | 67 + .../MovePlaylistEntryEndpointSummary.cs | 37 + .../RemovePlaylistEntryEndpoint.cs | 63 + .../RemovePlaylistEntryEndpointSummary.cs | 30 + .../UpdatePlaylist/UpdatePlaylistEndpoint.cs | 60 + .../UpdatePlaylistEndpointSummary.cs | 38 + .../Resources/Views/Home/Index.ar-SA.resx | 5 +- .../Resources/Views/Home/Index.de-DE.resx | 3 + .../Resources/Views/Home/Index.en-US.resx | 3 + .../Resources/Views/Home/Index.es-ES.resx | 3 + .../Resources/Views/Home/Index.fr-FR.resx | 3 + .../Resources/Views/Home/Index.it-IT.resx | 3 + .../Resources/Views/Home/Index.ja-JP.resx | 5 +- .../Core/Resources/Views/Home/Index.resx | 3 + .../Resources/Views/Home/Index.ro-RO.resx | 5 +- .../Resources/Views/Home/Index.uk-UA.resx | 5 +- .../Resources/Views/Home/Index.zh-CN.resx | 5 +- .../MusicLibrary/Albums/Item.ar-SA.resx | 12 + .../MusicLibrary/Albums/Item.de-DE.resx | 12 + .../MusicLibrary/Albums/Item.en-US.resx | 18 +- .../MusicLibrary/Albums/Item.es-ES.resx | 12 + .../MusicLibrary/Albums/Item.fr-FR.resx | 12 + .../MusicLibrary/Albums/Item.it-IT.resx | 12 + .../MusicLibrary/Albums/Item.ja-JP.resx | 12 + .../MusicLibrary/Albums/Item.resx | 18 +- .../MusicLibrary/Albums/Item.ro-RO.resx | 12 + .../MusicLibrary/Albums/Item.uk-UA.resx | 12 + .../MusicLibrary/Albums/Item.zh-CN.resx | 12 + .../MusicLibrary/Artists/Index.ar-SA.resx | 7 +- .../MusicLibrary/Artists/Index.de-DE.resx | 5 +- .../MusicLibrary/Artists/Index.en-US.resx | 5 +- .../MusicLibrary/Artists/Index.es-ES.resx | 5 +- .../MusicLibrary/Artists/Index.fr-FR.resx | 5 +- .../MusicLibrary/Artists/Index.it-IT.resx | 5 +- .../MusicLibrary/Artists/Index.ja-JP.resx | 7 +- .../MusicLibrary/Artists/Index.resx | 5 +- .../MusicLibrary/Artists/Index.ro-RO.resx | 7 +- .../MusicLibrary/Artists/Index.uk-UA.resx | 7 +- .../MusicLibrary/Artists/Index.zh-CN.resx | 7 +- .../MusicLibrary/Artists/Item.ar-SA.resx | 3 + .../MusicLibrary/Artists/Item.de-DE.resx | 3 + .../MusicLibrary/Artists/Item.en-US.resx | 9 +- .../MusicLibrary/Artists/Item.es-ES.resx | 3 + .../MusicLibrary/Artists/Item.fr-FR.resx | 3 + .../MusicLibrary/Artists/Item.it-IT.resx | 3 + .../MusicLibrary/Artists/Item.ja-JP.resx | 3 + .../MusicLibrary/Artists/Item.resx | 9 +- .../MusicLibrary/Artists/Item.ro-RO.resx | 3 + .../MusicLibrary/Artists/Item.uk-UA.resx | 3 + .../MusicLibrary/Artists/Item.zh-CN.resx | 3 + .../MusicLibrary/Tracks/Item.en-US.resx | 6 +- .../MusicLibrary/Tracks/Item.resx | 6 +- .../Views/Playlists/Index.ar-SA.resx | 51 + .../Views/Playlists/Index.de-DE.resx | 51 + .../Views/Playlists/Index.en-US.resx | 51 + .../Views/Playlists/Index.es-ES.resx | 51 + .../Views/Playlists/Index.fr-FR.resx | 51 + .../Views/Playlists/Index.it-IT.resx | 51 + .../Views/Playlists/Index.ja-JP.resx | 51 + .../Core/Resources/Views/Playlists/Index.resx | 51 + .../Views/Playlists/Index.ro-RO.resx | 51 + .../Views/Playlists/Index.uk-UA.resx | 51 + .../Views/Playlists/Index.zh-CN.resx | 51 + .../Resources/Views/Playlists/Item.ar-SA.resx | 138 + .../Resources/Views/Playlists/Item.de-DE.resx | 138 + .../Resources/Views/Playlists/Item.en-US.resx | 138 + .../Resources/Views/Playlists/Item.es-ES.resx | 138 + .../Resources/Views/Playlists/Item.fr-FR.resx | 138 + .../Resources/Views/Playlists/Item.it-IT.resx | 138 + .../Resources/Views/Playlists/Item.ja-JP.resx | 138 + .../Core/Resources/Views/Playlists/Item.resx | 138 + .../Resources/Views/Playlists/Item.ro-RO.resx | 138 + .../Resources/Views/Playlists/Item.uk-UA.resx | 138 + .../Resources/Views/Playlists/Item.zh-CN.resx | 138 + .../Resources/Views/Shared/_Layout.ar-SA.resx | 33 + .../Resources/Views/Shared/_Layout.de-DE.resx | 33 + .../Resources/Views/Shared/_Layout.en-US.resx | 33 + .../Resources/Views/Shared/_Layout.es-ES.resx | 33 + .../Resources/Views/Shared/_Layout.fr-FR.resx | 33 + .../Resources/Views/Shared/_Layout.it-IT.resx | 33 + .../Resources/Views/Shared/_Layout.ja-JP.resx | 33 + .../Core/Resources/Views/Shared/_Layout.resx | 33 + .../Resources/Views/Shared/_Layout.ro-RO.resx | 33 + .../Resources/Views/Shared/_Layout.uk-UA.resx | 33 + .../Resources/Views/Shared/_Layout.zh-CN.resx | 33 + .../Views/Shared/_NavMenu.ar-SA.resx | 3 + .../Views/Shared/_NavMenu.de-DE.resx | 3 + .../Views/Shared/_NavMenu.en-US.resx | 3 + .../Views/Shared/_NavMenu.es-ES.resx | 3 + .../Views/Shared/_NavMenu.fr-FR.resx | 3 + .../Views/Shared/_NavMenu.it-IT.resx | 3 + .../Views/Shared/_NavMenu.ja-JP.resx | 3 + .../Core/Resources/Views/Shared/_NavMenu.resx | 3 + .../Views/Shared/_NavMenu.ro-RO.resx | 3 + .../Views/Shared/_NavMenu.uk-UA.resx | 3 + .../Views/Shared/_NavMenu.zh-CN.resx | 3 + .../Core/Themes/ThemeAudioPlayerBuilder.cs | 9 +- .../Core/Themes/ThemeNavBuilder.cs | 1 + .../Core/Views/Home/Index.cshtml | 17 +- .../MusicLibrary/Albums/Item.cshtml | 188 +- .../MusicLibrary/Artists/Index.cshtml | 17 +- .../MusicLibrary/Artists/Item.cshtml | 13 +- .../Core/Views/Playlists/Index.cshtml | 207 + .../Core/Views/Playlists/Item.cshtml | 1076 +++++ .../Core/Views/Shared/_AudioPlayer.cshtml | 24 +- .../Views/Shared/_ThemeLayoutScripts.cshtml | 33 +- .../wwwroot/css/site.css | 176 + .../wwwroot/js/audio-player/audio-player.js | 417 +- .../wwwroot/js/playlists.js | 449 ++ .../Albums/AlbumLiteRowFixture.cs | 16 +- .../Artists/ArtistLiteRowFixture.cs | 10 +- .../Tracks/TrackLiteRowFixture.cs | 14 +- .../BookLibrary/BookLiteRowFixture.cs | 12 +- .../Playlists/PlaylistEntityFixture.cs | 85 + .../Playlists/PlaylistEntryEntityFixture.cs | 58 + .../LibraryScanSnapshotRepositoryTests.cs | 3 + .../Playlists/PlaylistRepositoryTests.cs | 485 +++ .../Core/UoW/LuminaDbContextTests.cs | 4 +- .../Dapper/SqliteGuidTypeHandlerTests.cs | 4 +- .../PlaylistAggregate/PlaylistTests.cs | 67 + .../LibraryOwnershipPolicyTests.cs | 73 +- .../EventualConsistencyMiddlewareTests.cs | 194 + .../ExceptionHandlingMiddlewareTests.cs | 5 +- 296 files changed, 18830 insertions(+), 367 deletions(-) create mode 100644 src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs create mode 100644 src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs create mode 100644 src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs create mode 100644 src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs create mode 100644 src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs create mode 100644 src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntryEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs create mode 100644 src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs create mode 100644 src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/PlaylistWindow.cs create mode 100644 src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs create mode 100644 src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs create mode 100644 src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs create mode 100644 src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs create mode 100644 src/Lumina.Domain/Common/Errors/Errors.Playlist.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs create mode 100644 src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs create mode 100644 src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs create mode 100644 src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs create mode 100644 src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx create mode 100644 src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx create mode 100644 src/Lumina.Presentation.Web/Core/Views/Playlists/Index.cshtml create mode 100644 src/Lumina.Presentation.Web/Core/Views/Playlists/Item.cshtml create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/playlists.js create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntryEntityFixture.cs create mode 100644 tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs create mode 100644 tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs diff --git a/docs/manual/index.md b/docs/manual/index.md index c19b691a..b3a2e806 100644 --- a/docs/manual/index.md +++ b/docs/manual/index.md @@ -36,7 +36,7 @@ Lumina is growing, and this is what works right now: - **Media libraries that scan themselves.** Point Lumina at a folder or a drive, tell it what kind of media lives there, and it gets to work discovering and indexing what it finds. Scans run in the background, report their progress as they go, and can be started, cancelled or resumed. - **Written content.** Add a written content library and Lumina scans it, cataloguing the books and e-books it contains and dressing them up with metadata for browsing in the client. Open one and it renders in the browser through a reader plugin; the EPUB and PDF readers are bundled and can be enabled per library. -- **Music.** Add a music library and Lumina indexes the artists, albums and tracks it contains, reading metadata from the tags inside the audio files. If you want more, enable a metadata provider and Lumina fills in the gaps from online sources, and artwork can come from your folders or from remote sources. +- **Music.** Add a music library and Lumina indexes the artists, albums and tracks it contains, reading metadata from the tags inside the audio files. If you want more, enable a metadata provider and Lumina fills in the gaps from online sources, and artwork can come from your folders or from remote sources. You can also build your own playlists, order them the way you want and play them in the browser. - **Metadata and artwork from plugins.** Plugins do the knowing. They supply the metadata and the artwork of a library, and you decide, library by library, which ones are switched on and which one wins when several of them recognize the same item. - **A file system browser.** Reach the drives, folders and files of the server machine from anywhere you can open the client, as if you were sitting right in front of it. Poke around, walk a path to its root or to its parent, and let Lumina generate thumbnails for what it finds. - **Accounts, roles, permissions and policies.** Create accounts, sign in with a password and optional two factor authentication, and hand out access through roles, fine grained permissions and policies that decide who may reach which library or content. Administrators manage all of it from the administration area. diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index e7cdfd01..937a0c55 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -73,7 +73,22 @@ Each artist is a card; selecting it opens the artist's page, and the card's acti The artist page is also where you edit the artist. It lists the artist's albums as cards, each leading to its own album page, followed by the artist's general information, contributors, ratings, genres, tags, aliases, areas and identifiers. The album page holds the album's information and its tracks, and the track page holds the track's details. The album page also shows the artwork Lumina stored for the album as a strip of thumbnails beside the main image, and selecting a thumbnail displays that image in place of the cover. Deleting an artist, album or track removes it from Lumina's catalogue; your files are not touched. -The music pages also play what they show. The artist page has a **Play all** control that plays the artist's releases in the order the page presents them, one release after another. The actions menu of a music library card on the home page, of an artist card, and of an album card offers **Play** and **Shuffle**. Play starts the library at its first artist and continues through the remaining artists in artist page order, starts the artist's discography in the order the artist page presents it, or starts the release in disc and track order. Shuffle starts the library, the artist's discography or the release with a list of up to 100 tracks sampled uniformly at random from every track of that scope, and continues in random order without repeating a track that is already queued. The album page has a **Play album** control that plays the release in disc and track order, and every track row has its own play control that plays just that track. The track page has a **Play track** control for the track it shows. Starting playback opens the player bar at the bottom of the window. It keeps playing while you move between pages, and the bar shows the track name, with the album name underneath when the track belongs to a named album, the progress of the current track and the volume, together with previous, play or pause, stop, next and repeat controls. When you expand it, it also shows the cover art, the current track name, the release type, the release name and year, the artist name, and a carousel of the album's stored artwork, next to the queue, where every entry carries its album cover, including when only one track is queued. Selecting an artwork in the carousel shows it as the main cover. The expanded queue moves the current track to the top whenever playback advances, so it stays visible even in a long list. The double chevron at the right points up to expand the bar and down to collapse it. Stop is the square control next to play or pause; in the condensed bar it stops playback and slides the bar out of view. +The music pages also play what they show. The artist page has a **Play all** control that plays the artist's releases in the order the page presents them, one release after another. The actions menu of a music library card on the home page, of an artist card, and of an album card offers **Play** and **Shuffle**. Play starts the library at its first artist and continues through the remaining artists in artist page order, starts the artist's discography in the order the artist page presents it, or starts the release in disc and track order. Shuffle starts the library, the artist's discography or the release with a list of up to 100 tracks sampled uniformly at random from every track of that scope, and continues in random order without repeating a track that is already queued. The album page has a **Play album** control that plays the release in disc and track order, and every track row has its own play control that plays just that track. The track page has a **Play track** control for the track it shows. Every track row on the album page also has an actions menu: **Add to playlist** opens the playlist picker for that track, **Add to play queue** appends it to the end of the player queue or starts it when the queue is empty, and **Play all from here** replaces the queue with that track and the rest of the album and starts playing. Starting playback opens the player bar at the bottom of the window. It keeps playing while you move between pages, and the bar shows the track name, with the album name underneath when the track belongs to a named album, the progress of the current track and the volume, together with previous, play or pause, stop, next and repeat controls. When you expand it, it also shows the cover art, the current track name, the release type, the release name and year, the artist name, and a carousel of the album's stored artwork, next to the queue, where every entry carries its album cover, including when only one track is queued. Selecting an artwork in the carousel shows it as the main cover. The expanded queue moves the current track to the top whenever playback advances, so it stays visible even in a long list. The double chevron at the right points up to expand the bar and down to collapse it. Stop is the square control next to play or pause; in the condensed bar it stops playback and slides the bar out of view. + +## Playlists + +The **Playlists** entry under Audio opens your playlists. A playlist survives signing out and back in, but the player queue itself does not. A full page reload still starts with an empty queue and a hidden player. + +From the playlists page you can open a playlist or select **Create** to open the dedicated page that creates a new playlist with a name and an optional description. Selecting an existing playlist opens its own page, which shows its tracks in order and lets you: + +- **Add a track** by choosing a music library, then an artist, an album and a track, and selecting **Add**. A track can appear more than once in the same playlist. +- **Reorder the tracks** by dragging a row by its handle, or with the up and down controls on each row. The order is saved immediately. +- **Remove a track** from the playlist. The track itself, and the file behind it, are not touched. +- **Play a single track** with its play control, or **Play playlist** to hand the whole ordered list to the player in one go. While something is playing, the expanded player's **Add to playlist** button appends its current queue to one of your playlists. +- **Add a whole library, artist or album** from the card menu of its page: choose **Add to playlist**, pick a playlist, and the tracks of that scope are appended in catalogue order. The same dialog lets you create a playlist when you have none yet. +- **Edit the name and description**, and **delete the playlist** when you no longer need it. Deleting a playlist never deletes any track. + +The playlist reflects the catalogue at the moment you open it. If a track is deleted from a library after it was added to a playlist, its row stays in the playlist as an unavailable track so you can remove it deliberately. Long playlists are shown in pages; select **Load more** to show the next page. ## Editing what is catalogued diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md index 2018e742..bc32e032 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0006.md @@ -33,7 +33,7 @@ SQLite Write-Ahead Logging (`PRAGMA journal_mode=WAL`) and a busy timeout are en ### Risks and Tradeoffs | Risk | Mitigation Strategy | |-------------------------------|-------------------------------------------------------------------| -| Raw SQL duplication | All raw SQL is confined to the two bulk repositories, behind the repository and unit of work abstractions | +| Raw SQL duplication | All raw SQL is confined to the bulk repositories (the scan jobs and the documented playlist append), behind the repository and unit of work abstractions | | Concurrency errors | WAL and a busy timeout are enabled at startup, and the bulk operations run on dedicated connections | | Layer integrity | Dapper is referenced only by the DataAccess layer | @@ -47,4 +47,26 @@ Bulk statements would run on the same connection as the tracked queries of the j ### 2. Third party bulk library (for example EF Core bulk extensions) A dedicated bulk extension library would abstract the raw SQL. -**Rejected**: Dapper is a small, widely adopted and dependency free mapper, and the amount of raw SQL is small and confined to two repositories. See the ADRs of the scan subsystem for the exact statements. +**Rejected**: Dapper is a small, widely adopted and dependency free mapper, and the amount of raw SQL is small and confined to the bulk repositories. See the ADRs of the scan subsystem for the exact statements, and the amendment below for the playlist append. + +## Amendment: Playlist Whole-Library Appends (2026-10-20) + +The playlist feature needs to append a whole library, which can contain hundreds of thousands of tracks, to a playlist in one request. The Entity Framework change tracker cannot materialize that graph, so `PlaylistRepository.AddEntriesAsync` performs the append with parameterized multi-row `INSERT` statements in bounded batches. + +Unlike the scan jobs, this bulk operation deliberately uses the connection and the transaction of the request's unit of work, not a dedicated connection. The request middleware already holds the SQLite write transaction, and a dedicated connection would wait on that lock while the request waits on the append. Sharing the request transaction keeps the append atomic with the ownership check and the activity update, and the busy timeout plus the unique `(PlaylistId, Position)` index turn a concurrent append into a mapped conflict instead of a duplicate position. + +The exception is confined to the append and the rare sparse-key rebalance in `PlaylistRepository` and is documented in the class remarks. Moves and removals use Entity Framework `ExecuteUpdateAsync` and `ExecuteDeleteAsync` on their normal path, so they keep the model, the transaction and the error mapping. The rebalance uses raw SQL only when repeated midpoint moves exhaust the numeric gap between two neighbors; it respaces the order keys through a temporary table inside the request transaction. + +## Amendment: Playlist Scope Ordering and Rollback (2026-10-21) + +A whole library, artist or album scope is now appended with one `INSERT ... SELECT` statement in `PlaylistRepository.AddScopeEntriesAsync`. The statement joins the catalogue tables, orders the tracks with `ROW_NUMBER()` in SQLite and computes the sparse positions as part of the insert, so the scope is never materialized, sorted in memory or sent to the data access layer as a list of Ids. Explicit track lists still use the batched `AddEntriesAsync` path, because that list is already in memory. + +An append that fails or is cancelled rolls the request transaction back explicitly. The context records that rollback, and the eventual consistency middleware skips the commit and logs it when the response still reports success, instead of committing a partially written operation. + +## Amendment: Request Transaction Ownership and Aborted Requests (2026-10-21) + +The eventual consistency middleware now begins, commits and rolls back the request transaction through `IUnitOfWork`, so the transaction boundary follows the unit of work instead of the `DbContext` being used directly. The commit-before-publish sequence of ADR-0002 is unchanged. + +An aborted request is no longer left at its default success status: the exception handling middleware reports it as `499 Client Closed Request` and rethrows. The eventual consistency middleware therefore decides from the response status alone. It commits a 2xx response and rolls back every other response, including an abort, and it deliberately does not consult the request abort token, because that token can already be cancelled after a successful operation whose response was already sent. + +This replaces the in-context rollback marker and the repository's rollback of the ambient request transaction described in the previous amendment. A repository now only commits or rolls back a transaction it opened itself, which happens when it runs without an ambient request transaction. A partially written append is therefore discarded by the middleware's rollback, not by a signal from the repository. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md index 46b8df6e..32fd843b 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0014.md @@ -82,3 +82,17 @@ Introduce a generic persistence engine driven by a per-aggregate profile describ Stop modeling shared references as a shared table keyed by name, and store them per aggregate, removing the duplicate-key-in-graph class of bug at the source. **Rejected**: it requires a database schema change and changes query behavior for shared references, which is out of scope. The shared tables are kept, and the concern is handled where it belongs, in the persistence toolkit. + +## Amendment: Set-Based Playlist Entry Operations (2026-10-20) + +The playlist entries are mutated by set-based storage operations because a playlist can hold a whole library. The batched raw append and the `ExecuteUpdateAsync` and `ExecuteDeleteAsync` move and removal statements bypass the change tracker and therefore also bypass the auditing interceptor. + +Those operations stamp `UpdatedOnUtc` and `UpdatedBy` on the playlist row themselves, stamp the creation or update audit columns of the entry rows they write, and increment the playlist concurrency token, in the same transaction. This is the only exception to the rule that the auditing interceptor is the only writer of the audit columns. Details edits still go through `EditableValuesCopier` and leave the audit columns to the interceptor. The exception is confined to `PlaylistRepository` and is documented in the class remarks. + +Ordering is storage owned as well. The unique index on `(PlaylistId, Position)` is the enforced invariant, and the positions are sparse order keys rather than dense indices. A move normally changes one key to the midpoint between its new neighbors, and a removal deletes one row, so neither rewrites the following range. If repeated midpoint moves exhaust the numeric gap between two neighbors, a rare rebalance respaces the keys with a temporary table and two passes so the unique index is never violated. The domain only rejects duplicate positions on reconstitution, so a storage gap is readable instead of making the playlist impossible to load. + +## Amendment: Playlist Entry Count and Change Detection (2026-10-21) + +The playlist row now carries a denormalized `EntryCount`, maintained by the set-based append and removal operations in the same statement that updates the playlist activity time and concurrency token. Window reads, moves and the single-add read-back use that column instead of counting the entries of the playlist, so none of them scan an index proportional to the playlist size. + +Details edits still go through `EditableValuesCopier`, but the copier now compares the incoming value with the tracked value before assigning it and marks only an actual change as modified. `PlaylistRepository.UpdateAsync` also compares the tracked original values explicitly before it decides to increment the concurrency token, so a no-op save neither restamps the row nor bumps its version. diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md index ee4eefe1..89c93228 100644 --- a/docs/technical/domain/UbiquitousLanguage.md +++ b/docs/technical/domain/UbiquitousLanguage.md @@ -112,7 +112,8 @@ - PodcastLibrary (root: PodcastLibrary, entities: Podcast, PodcastEpisode) - WrittenContentLibrary (root: WrittenContentLibrary, entities: Book, EBook, BookSeries, ComicBook, ComicSeries, Magazine, MagazineIssue, Newspaper, Manga, GraphicNovel, AcademicPaper, SheetMusic, Screenplay) - PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster) -- UserProfile (root: User, entities: Playlist, Collection) +- UserProfile (root: User, entities: Collection) +- PlaylistManagement (root: Playlist, entities: PlaylistEntry) - SupplementaryContentLibrary (root: SupplementaryContentLibrary, entities: SubtitleFile, Lyrics, LanguageTrack) - FileSystemManagement (root: File, entities: Stream) @@ -208,6 +209,10 @@ - MediaItemRemoved - PlaylistCreated - PlaylistUpdated +- PlaylistEntryAdded +- PlaylistEntryRemoved +- PlaylistEntriesReordered +- PlaylistDeleted - UserPreferencesChanged - MetadataUpdated - FileTranscoded @@ -222,6 +227,8 @@ - UserExperience - Aggregates: UserProfile - Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService +- PlaylistManagement + - Aggregates: Playlist - ContentDelivery - Aggregates: FileSystemManagement - Services: StreamingService, ContentSynchronizationService diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 3163df87..7e105e7a 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -168,6 +168,8 @@ Known page keys: | `shared/audio-player/queue-item` | The queue item of the audio player bar. | | `shared/audio-player/playlist-item` | The playlist item of the audio player bar. | | `library/written-content-library/book-library/books/index` | The books browsing page. | +| `playlists/index` | The page that lists and deletes the playlists of the current user. | +| `playlists/item` | The page that creates a playlist, or edits, reorders, plays and deletes an existing playlist of the current user. The `isNew` page data field tells the two modes apart. | | `shared/file-system-browser` | The file system browser component shell. | | `shared/file-system-browser/tree-node` | The tree view node of the file system browser. | | `shared/file-system-browser/explorer-item` | The file system entry of the file system browser. | @@ -244,6 +246,8 @@ The theme owns the position, orientation and size of the bar, and it owns the ro | The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area releases the room the theme reserved for the bar. | | The main content element | `audio-player-bar-expanded` class | The bar is expanded. This is the layout-neutral state for the main content element's own adjustment. | | The expand and collapse control | `id="audio-player-expand-toggle"` | A focusable control, such as a `button`, that expands or collapses the bar. Its label may describe the action in the theme's own layout. | +| The queue-to-playlist combo box | `data-audio-player-playlist-combobox` | A standard application combo box (`enlightenment-combobox`) in the expanded area that lists the playlists of the current user. Its root carries the hook; its selected text carries the chosen playlist Id in `data-value`. When the theme does not render the hook, the player builds a built-in combo box of the same markup and places it in a `audio-player-queue-area` wrapper above the queue, so the action never becomes a new column of the expanded layout. | +| The queue-to-playlist button | `data-audio-player-add-queue-to-playlist` | A focusable control in the expanded area that appends the current queue, in order, to the playlist selected in the combo box. When the theme does not render it, the player builds a built-in button next to the combo box. The player disables it while the queue is empty, while no playlist exists, and while an add is in flight. | The `shared/audio-player` template receives the following model: @@ -253,7 +257,7 @@ The `shared/audio-player` template receives the following model: | `assetBase` | The base URL of the theme assets, used by the theme template to reference its own assets. | | `queueItemTemplate` | The raw source of the `shared/audio-player/queue-item` sub template, inlined by the application into a plain text script element. | | `playlistItemTemplate` | The raw source of the `shared/audio-player/playlist-item` sub template, inlined by the application into a plain text script element. | -| `strings` | The localized strings of the bar, keyed by their resource names. A shell template uses `toggleExpanded`, `previous`, `next`, `stop`, `repeat`, `repeatOff`, `repeatAll`, `repeatOne`, `queue` and `albumArtwork` for its controls; the player reads the play, pause, mute, unmute, volume, seek and buffering labels from the global scripts configuration instead, so a themed shell does not need to render them. | +| `strings` | The localized strings of the bar, keyed by their resource names. A shell template uses `toggleExpanded`, `previous`, `next`, `stop`, `repeat`, `repeatOff`, `repeatAll`, `repeatOne`, `queue`, `albumArtwork`, `addQueueToPlaylist`, `addToPlaylist`, `selectPlaylist` and `add` for its controls; the player reads the play, pause, mute, unmute, volume, seek, buffering, success and failure labels from the global scripts configuration instead, so a themed shell does not need to render them. | The bundled themes reserve the room for their bottom bar like this. It is an example of a bottom layout, not a required layout: @@ -369,7 +373,7 @@ The sub templates are rendered client side by the audio player script with the s | Template | Fields | | --- | --- | | `queue-item` | `entryId` (the identity of this occurrence in the queue), `index` (the one based position in the queue), `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration` (the formatted `m:ss` duration), `durationSeconds`, `coverArtUrl` (the resolved cover art URL, which is the music placeholder when the entry has no artwork), `isCurrent`, `isPlayed`, `isLast`, `isContinuation` (the entry was added by the autoplay continuation) and `isShuffled` (the entry was added by a shuffle batch). The item root must keep the `audio-player-queue-item` class, the stylesheet hook of a queue item: the player appends the rendered element as-is, so the class is what lets the theme style it. The player writes `is-current`, `is-played`, `is-continuation` and `is-shuffled` on the root itself, so a theme item does not need to render those state classes, and it writes `data-audio-player-queue-entry-id`, so a theme item does not need to render the identity either. | -| `playlist-item` | `index`, `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration`, `durationSeconds`, `coverArtUrl` and `isCurrent`. The item root must keep the `audio-player-playlist-item` class, the stylesheet hook of a playlist item. Saved playlists do not exist yet, so the shell inlines this sub template for theme authors, but nothing renders it yet; the playlist feature renders the entries of a playlist from it. | +| `playlist-item` | `index`, `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration`, `durationSeconds`, `coverArtUrl` and `isCurrent`. The item root must keep the `audio-player-playlist-item` class, the stylesheet hook of a playlist item. The shell inlines this sub template for theme authors, but the player does not render a saved playlist list with it yet; the saved playlist page renders its own rows from the page data described below. | A theme can omit either sub template: the player then renders that part with its own built-in markup. When a theme replaces the shell, it must keep the two plain text script element ids above, the element hooks of the bar, and the `audio-player-container`, `not-shown` and `expanded` classes the player toggles. @@ -470,6 +474,71 @@ Page templates are rendered into a content section that the layout wraps. A page {{/scripts}} ``` +#### The Playlist Pages + +`playlists/index` receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `getPlaylistsUrl` | The route that returns the playlists of the current user. | +| `addUrl` | The route of the dedicated page that creates a playlist. | +| `itemUrl` | The route template of a playlist page. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the playlist. | +| `deleteUrl` | The route template that deletes a playlist. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the playlist. | +| `antiforgeryToken` | The anti-forgery token the page submits with its mutating requests. | +| `strings` | The localized strings of the page, keyed by their resource names. | + +`playlists/item` receives a model with the following fields: + +| Field | Content | +| --- | --- | +| `isNew` | `true` on the create page, `false` on the page of an existing playlist. The same page key serves both modes. | +| `playlistId` | The Id of the playlist the page shows, or the empty Id on the create page. | +| `playlistJson` | The playlist metadata and only the first window of its ordered entries, serialized as JSON. `entryCount` is the total number of entries. Each entry carries `mediaItemId` and `mediaItemType`, which are generic across media kinds, together with the generic display fields `libraryId`, `collectionId`, `creatorId`, `mediaItemTitle`, `collectionTitle`, `creatorName`, `durationInSeconds` and `coverPath`. For a music entry, the collection is the album and the creator is the artist. On the create page it is an empty music playlist. | +| `entriesWindowSize` | The number of entries in the first window. The page fetches the next windows with `getPlaylistUrl` and the same size. | +| `createPlaylistUrl` | The route that creates a playlist. Only meaningful when `isNew` is `true`. | +| `itemUrl` | The route template of the page of an existing playlist. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the playlist, and the page script navigates to it after a successful create. | +| `getPlaylistUrl` | The route that returns a window of the playlist. It takes `offset` and `limit` query parameters and returns `entryCount` with the window. The limit is a response-window bound of at most 1000 entries, not a cap on the playlist size. | +| `updatePlaylistUrl` | The route that updates the name and description of the playlist. | +| `deletePlaylistUrl` | The route that deletes the playlist. | +| `addEntryUrl` | The route that adds a track to the playlist. | +| `removeEntryUrl` | The route template that removes an entry. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the entry. | +| `moveEntryUrl` | The route that moves one entry of the playlist to a new position. The empty `00000000-0000-0000-0000-000000000000` entry segment is replaced by the entry Id; the body carries `targetPosition`. | +| `getEnabledLibrariesUrl` | The route that lists the media libraries the current user can browse. | +| `getArtistsUrl` | The route that lists the artists of a music library. It takes `libraryId` as a query parameter. | +| `getArtistAlbumsUrl` | The route template that lists the releases of an artist. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the artist, and the library Id is passed as a query parameter. | +| `getAlbumTracksUrl` | The route template that lists the tracks of an album. The two `00000000-0000-0000-0000-000000000000` segments are replaced by the Ids of the artist and the album, and the library Id is passed as a query parameter. | +| `indexUrl` | The route of the playlists page. | +| `antiforgeryToken` | The anti-forgery token the page submits with its mutating requests. | +| `strings` | The localized strings of the page, keyed by their resource names. | + +The fallback views keep these element hooks, which the application script drives: on the list page, `playlists-container`, `no-playlists` and `playlist-count`; on the item page, `playlist-details-form`, `playlist-title`, `playlist-name-input`, `playlist-description-input`, `save-playlist-button`, `cancel-playlist-button`, `play-playlist-button`, `delete-playlist-button`, `playlist-entries`, `no-tracks`, `load-more-entries-button`, `playlist-library-combobox`, `playlist-artist-combobox`, `playlist-album-combobox`, `playlist-track-combobox`, `add-track-button` and `no-music-libraries`. The four track picker controls are standard application combo boxes, not native `select` elements. A theme that restructures a page must keep the hooks the page script needs for that page. + +The playlist rows use the same play affordance contract as the music pages: an element with `data-audio-player-play` and the `data-track-id`, `data-library-id`, `data-album-id`, `data-artist-id`, `data-title`, `data-album-title`, `data-duration` and `data-cover-art-path` attributes is handed to the global player by event delegation. The page fills `data-track-id` from the entry `mediaItemId`, because a music entry references a track. The Play playlist control fetches every window of the playlist in order, builds an explicit queue from the playable entries and starts it through the player control API, so a theme template must keep the `play-playlist-button` hook for that control. + +The playlist rows are reordered by dragging the handle with the `playlist-entry-drag-handle` class, and the row carries the `is-dragging` class while it is being dragged. The up and down controls remain available for keyboard and touch users, and the page uses the `playlist-entry-move-up`, `playlist-entry-move-down` and `playlist-entry-remove` classes to disable them while an entry mutation is in flight. A theme template that changes the row structure must keep the `playlist-entry` class and the `data-entry-id` attribute on the row, so the page script can find the row and commit its new position. + +#### The Shared Add to Playlist Action + +The music library card on the home page, the artist cards, the album cards and the actions menu of an album track row share one add-to-playlist action. The action is a menu item with the `card-action-add-to-playlist` class in both cases. Their click handler calls `window.LuminaPlaylists.showAddScopeDialogAsync(scope)`, where `scope` carries `libraryId`, the optional `artistId`, `albumId` and `trackId`, the `title` shown in the dialog, the page-local `addToPlaylistLabel`, and the optional `returnFocus` element that gets the focus back when the dialog closes. The helper is provided by `wwwroot/js/playlists.js`, which every layout loads. The page passes its own localized label from its page resource as `addToPlaylistLabel`. + +The dialog is rendered by the application, not by the theme: it is a standard application dialog surface with a standard `enlightenment-combobox` of the playlists of the current user. When the scope carries a `trackId`, the dialog appends that single track through the single entry route. Otherwise, the server resolves the ordered track Ids of the scope and appends them to the selected playlist in one batch request. In both cases it shows the result notification and dispatches the `lumina:playlist-updated` event so an open playlist page refreshes. A theme that renders the dialog itself does not get this behavior; it must keep the action wired to the shared helper or reimplement the whole flow. + +The layout provides the shared configuration as `window.playlistConfiguration`: + +| Field | Content | +| --- | --- | +| `getPlaylistsUrl` | The route that returns the playlists of the current user. | +| `addPlaylistEntryUrl` | The route that appends one track to a playlist. The empty `00000000-0000-0000-0000-000000000000` segment is replaced by the playlist Id; the body carries `trackId`. | +| `addScopeEntriesUrl` | The route that appends a whole library, artist or album scope to a playlist. The empty `00000000-0000-0000-0000-000000000000` segment is replaced by the playlist Id; the body carries `libraryId` and the optional `artistId` and `albumId`, and the server resolves and appends the tracks in catalogue order in the database. | +| `createPlaylistUrl` | The route of the dedicated create playlist page, linked from the empty state of the dialog. | +| `strings` | The localized dialog labels, including `selectPlaylist`, `noPlaylists`, `createPlaylist`, `tracksAdded`, `tracksAddFailed` and `noTracksToAdd`. | + +The player queue action does not use `addToPlaylistLabel`. Its label comes from the `PlaylistAddToPlaylist` layout resource, exposed to the player as `strings.addToPlaylist` in the audio player configuration. + +#### The Album Track Actions Menu + +Every rendered track row of the album details page carries the same `card-actions-trigger` button with the vertical dots as the card menus, plus the `track-actions-trigger` class that places it inline in the row. The page script creates the same `card-actions-menu` markup on demand. The menu has three application actions: `card-action-add-to-playlist` opens the shared add-to-playlist dialog for that track, `card-action-add-to-queue` calls `window.LuminaAudioPlayer.instance.appendToQueueAsync(descriptor)`, and `card-action-play-all-from-here` calls `playAsync` with an explicit queue built from the clicked track and every track that follows it in the album order. The player starts the clicked track for the last action, and replaces the queue. A theme that renders the album page must keep the track row markup and the script behavior, or provide its own equivalent. + ### The Scripts Section JavaScript is always allowed in themes: script elements in templates are served and rendered as-is, and script files under `assets/` are served normally. A theme relies on scripts for the client side navigation of the application, because pages are swapped in place by the global AJAX navigator, so themes are expected to ship their own JavaScript. Because JavaScript is enabled, *themes can execute malicious code*, so, be aware about the source of your installed themes! Themes bundled with the application are reviewed and safe. 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 index 9a74fa8a..45540f8c 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRow.cs @@ -9,35 +9,17 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A /// /// 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; } - - /// - /// Gets the path of the image representing the album, if available. - /// - public string? CoverPath { get; init; } - - /// - /// Gets the release year of the album (the re-release year, if available, or the original release year), if known. - /// - public int? ReleaseYear { get; init; } - - /// - /// Gets the set of types of the release. - /// - public List? ReleaseTypes { get; init; } -} +/// The Id of the album. +/// The title of the album. +/// The number of tracks of the release. +/// The path of the image representing the album, if available. +/// The release year of the album (the re-release year, if available, or the original release year), if known. +/// The set of types of the release. +public sealed record AlbumLiteRow( + Guid Id, + string Title, + int TotalTracks, + string? CoverPath, + int? ReleaseYear, + List? ReleaseTypes +); 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 index 31970314..a9a58483 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRow.cs @@ -7,20 +7,11 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A /// /// 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; } - - /// - /// Gets the path of the image representing the artist, if available. - /// - public string? CoverPath { get; init; } -} +/// The Id of the artist. +/// The name of the artist. +/// The path of the image representing the artist, if available. +public sealed record ArtistLiteRow( + Guid Id, + string Name, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs index d2cf7182..941e5ec0 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDto.cs @@ -7,40 +7,19 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// Read model of a track returned by a randomized shuffle query, carrying everything the client needs to queue and play it. /// -public sealed record ShuffleTrackRowDto -{ - /// - /// Gets the Id of the track. - /// - public required Guid TrackId { get; init; } - - /// - /// Gets the title of the track. - /// - public required string Title { get; init; } - - /// - /// Gets the duration of the track in seconds. - /// - public int DurationInSeconds { get; init; } - - /// - /// Gets the Id of the album the track belongs to. - /// - public required Guid AlbumId { get; init; } - - /// - /// Gets the title of the album the track belongs to. - /// - public required string AlbumTitle { get; init; } - - /// - /// Gets the Id of the artist the album belongs to. - /// - public required Guid ArtistId { get; init; } - - /// - /// Gets the path of the cover of the album, if available. - /// - public string? CoverPath { get; init; } -} +/// The Id of the track. +/// The title of the track. +/// The duration of the track in seconds. +/// The Id of the album the track belongs to. +/// The title of the album the track belongs to. +/// The Id of the artist the album belongs to. +/// The path of the cover of the album, if available. +public sealed record ShuffleTrackRowDto( + Guid TrackId, + string Title, + int DurationInSeconds, + Guid AlbumId, + string AlbumTitle, + Guid ArtistId, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs new file mode 100644 index 00000000..50968d0c --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackAccessSummaryDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Data transfer object for the access information of a set of existing tracks. +/// +/// The number of distinct requested tracks that exist. +/// The distinct Ids of the media libraries that contain those tracks. +[DebuggerDisplay("TrackCount: {TrackCount}; Libraries: {LibraryIds.Count}")] +public sealed record TrackAccessSummaryDto( + int TrackCount, + IReadOnlyList LibraryIds +); 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 index 33275f1a..6107f315 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRow.cs @@ -7,30 +7,15 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// 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; } - - /// - /// Gets the duration of the track in seconds. - /// - public int DurationInSeconds { get; init; } -} +/// 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. +/// The duration of the track in seconds. +public sealed record TrackLiteRow( + Guid Id, + string Title, + int TrackNumber, + int? DiscNumber, + int DurationInSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs index 9a2e1b96..8e0966da 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRow.cs @@ -7,25 +7,13 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookL /// /// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list. /// -public sealed record BookLiteRow -{ - /// - /// Gets the Id of the book. - /// - public required Guid Id { get; init; } - - /// - /// Gets the title of the book. - /// - public required string Title { get; init; } - - /// - /// Gets the release year of the book (re-release year, if available, or original release year), if known. - /// - public int? ReleaseYear { get; init; } - - /// - /// Gets the path of the image representing the cover of the book, if available. - /// - public string? CoverPath { get; init; } -} +/// The Id of the book. +/// The title of the book. +/// The release year of the book (re-release year, if available, or original release year), if known. +/// The path of the image representing the cover of the book, if available. +public sealed record BookLiteRow( + Guid Id, + string Title, + int? ReleaseYear, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs new file mode 100644 index 00000000..e2c5893f --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistBulkAddResultDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for the result of appending entries to a playlist in one bulk operation. +/// +/// The sparse order key of the first appended entry. +/// The number of entries appended. +[DebuggerDisplay("FirstPosition: {FirstPosition}; AddedCount: {AddedCount}")] +public sealed record PlaylistBulkAddResultDto( + long FirstPosition, + int AddedCount +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs new file mode 100644 index 00000000..9604b553 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistDetailsDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// A stored playlist together with a window of its entries and their display data. +/// +/// The stored playlist. +/// The requested window of entries. +public sealed record PlaylistDetailsDto( + PlaylistEntity Playlist, + IReadOnlyList Entries +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs new file mode 100644 index 00000000..d866ac25 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDisplayDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Display data of the media item referenced by a playlist entry, together with its collection and creator. +/// +/// The Id of the track. +/// The title of the track. +/// The duration of the track in seconds. +/// The Id of the media library that contains the track. +/// The Id of the album that contains the track. +/// The title of the album that contains the track. +/// The Id of the artist that produced the track. +/// The name of the artist that produced the track. +/// The path of the cover art of the album, if available. +public sealed record PlaylistEntryDisplayDto( + Guid TrackId, + string TrackTitle, + int DurationInSeconds, + Guid LibraryId, + Guid AlbumId, + string AlbumTitle, + Guid ArtistId, + string ArtistName, + string? CoverPath +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs new file mode 100644 index 00000000..e74dd3a6 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistEntryDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// A stored playlist entry together with the display data of the media item it references and its dense display position. +/// +/// The stored entry. +/// The display data of the referenced media item, or when it no longer exists. +/// The dense zero based position shown to the client. +public sealed record PlaylistEntryDto( + PlaylistEntryEntity Entry, + PlaylistEntryDisplayDto? Display, + int DisplayPosition +); diff --git a/src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs b/src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs new file mode 100644 index 00000000..8ee7901c --- /dev/null +++ b/src/Lumina.Application/Common/DTO/Playlists/PlaylistSummaryDto.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +#endregion + +namespace Lumina.Application.Common.DTO.Playlists; + +/// +/// Data transfer object for a playlist in a list, without its entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +public sealed record PlaylistSummaryDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs new file mode 100644 index 00000000..7b9bcd53 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntity.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Playlists; + +/// +/// Repository entity for a playlist. +/// +[DebuggerDisplay("Id: {Id}; Name: {Name}; Type: {Type}")] +public class PlaylistEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the playlist. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the user that owns the playlist. + /// + public required Guid UserId { get; set; } + + /// + /// Gets or sets the name of the playlist. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the description of the playlist, if applicable. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the kind of media the playlist holds. + /// + public required PlaylistType Type { get; set; } + + /// + /// Gets or sets the ordered entries of the playlist. + /// + public List Entries { get; set; } = []; + + /// + /// Gets or sets the number of entries the playlist holds. + /// + /// + /// The count is maintained by the set-based entry operations in the same statement that appends or removes entries and updates the + /// playlist, so reading a window of a very large playlist never has to count its entries. + /// + public int EntryCount { get; set; } + + /// + /// Gets or sets the concurrency token of the playlist. + /// + public long Version { 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/Playlists/PlaylistEntryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntryEntity.cs new file mode 100644 index 00000000..787c4375 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Playlists/PlaylistEntryEntity.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Playlists; + +/// +/// Repository entity for an ordered entry of a playlist. +/// +/// +/// The entry references a media item by its Id and by the kind of media item, without a foreign key, so a playlist survives the deletion +/// of the item it references and the entry can be shown to its owner so that it can be removed. +/// +[DebuggerDisplay("Id: {Id}; MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")] +public class PlaylistEntryEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the entry. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the playlist the entry belongs to. + /// + public required Guid PlaylistId { get; set; } + + /// + /// Gets or sets the Id of the media item referenced by the entry. + /// + public required Guid MediaItemId { get; set; } + + /// + /// Gets or sets the kind of media item referenced by the entry. + /// + public PlaylistMediaItemType MediaItemType { get; set; } + + /// + /// Gets or sets the sparse order key of the entry in the ordered entries of the playlist. + /// + public long Position { get; set; } + + /// + /// Gets or sets the time and date when the entry was added. + /// + public DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entry. + /// + public Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entry was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entry. + /// + public Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs index 3e651d1f..e06452d0 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/ITrackRepository.cs @@ -129,4 +129,12 @@ public interface ITrackRepository : IRepository, /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the number of tracks in that exist, together with the distinct Ids of the libraries that contain them. + /// + /// The Ids of the tracks whose access information is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the access summary of the existing tracks, or an error. + Task> GetAccessInfoByIdsAsync(IReadOnlyCollection trackIds, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs new file mode 100644 index 00000000..4d4ad251 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Playlists/IPlaylistRepository.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Common.Actions; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Playlists; + +/// +/// Interface for the repository for playlists. +/// +public interface IPlaylistRepository : IRepository, + IInsertRepositoryAction, + IUpdateRepositoryAction, + IDeleteByIdRepositoryAction +{ + /// + /// Gets the playlist identified by when it belongs to the user identified by , if it exists. + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// Whether the entries of the playlist should be loaded together with the playlist itself. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist identified by and owned by , + /// when no such playlist exists, or an error. + /// + Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default); + + /// + /// Gets the playlists of the user identified by , ordered by their most recent activity. + /// + /// The Id of the user whose playlists are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the playlists of the user, or an error. + Task>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken); + + /// + /// Gets the playlist identified by together with the display details of the media items its entries reference, + /// when the playlist belongs to the user identified by . + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist details, when no such playlist exists, or an error. + /// + Task> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken); + + /// + /// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by + /// , using batched bulk inserts, and updates the activity time of the playlist in the same transaction. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Ids of the media items to append, in order. Duplicates are kept. + /// The kind of media item referenced by every appended entry. + /// The Ids to assign to the appended entries, in the same order as , or to generate them. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + Task> AddEntriesAsync(Guid playlistId, Guid userId, IReadOnlyList mediaItemIds, PlaylistMediaItemType mediaItemType, IReadOnlyList? entryIds, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Appends every media item of a library, an artist or an album to the end of the ordered entries of a playlist of the user identified by + /// , in catalogue order, without materializing the scope. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Id of the library whose media items are appended. + /// The Id of the artist the scope is limited to, or for every artist of the library. + /// The Id of the album the scope is limited to, or for every album of the scope. + /// The kind of media item referenced by every appended entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + Task> AddScopeEntriesAsync(Guid playlistId, Guid userId, Guid libraryId, Guid? artistId, Guid? albumId, PlaylistMediaItemType mediaItemType, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Moves one entry of a playlist of the user identified by to a new dense position by changing only its + /// sparse order key, and updates the activity time of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is moved. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to move. + /// The new zero based position of the entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful move, or an error. + Task> MoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, int targetPosition, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Removes one entry of a playlist of the user identified by by deleting only that row, and updates the + /// activity time of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is removed. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to remove. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either zero, because sparse positions need no repositioning, or an error. + /// + Task> RemoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, DateTime updatedOnUtc, CancellationToken cancellationToken); + + /// + /// Gets the entry that was just appended to a playlist of the user identified by , together with the display details of the track it references. + /// + /// The Id of the playlist the entry must belong to. + /// The Id of the user the playlist must belong to. + /// The Id of the appended entry to get. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the entry details, when the entry does not exist in that playlist of the user, or an error. + /// + Task> GetAppendedEntryDetailsForUserAsync(Guid playlistId, Guid userId, Guid entryId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index 586f522a..379ee478 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; @@ -155,6 +156,11 @@ public interface IUnitOfWork /// IMusicPlayRecordRepository MusicPlayRecordRepository { get; } + /// + /// Gets the playlist repository. + /// + IPlaylistRepository PlaylistRepository { get; } + /// /// Saves the changes made to the database. /// diff --git a/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs new file mode 100644 index 00000000..c5df9221 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntriesRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class AddPlaylistEntriesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static AddPlaylistEntriesCommand ToCommand(this AddPlaylistEntriesRequest request, string? playlistId) + { + return new AddPlaylistEntriesCommand(playlistId, request.TrackIds); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs new file mode 100644 index 00000000..7ffcd8c2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistEntryRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class AddPlaylistEntryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static AddPlaylistEntryCommand ToCommand(this AddPlaylistEntryRequest request, string? playlistId) + { + return new AddPlaylistEntryCommand(playlistId, request.TrackId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs new file mode 100644 index 00000000..10b678db --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class AddPlaylistScopeEntriesRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static AddPlaylistScopeEntriesCommand ToCommand(this AddPlaylistScopeEntriesRequest request, string? playlistId) + { + return new AddPlaylistScopeEntriesCommand(playlistId, request.LibraryId, request.ArtistId, request.AlbumId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs new file mode 100644 index 00000000..83d07c2d --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/CreatePlaylistRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class CreatePlaylistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static CreatePlaylistCommand ToCommand(this CreatePlaylistRequest request) + { + return new CreatePlaylistCommand(request.Name, request.Description, request.Type); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs new file mode 100644 index 00000000..79f0ff93 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/MovePlaylistEntryRequestMapping.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class MovePlaylistEntryRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The Id of the entry to move, taken from the route. + /// The converted command. + public static MovePlaylistEntryCommand ToCommand(this MovePlaylistEntryRequest request, string? playlistId, string? playlistEntryId) + { + return new MovePlaylistEntryCommand(playlistId, playlistEntryId, request.TargetPosition); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs new file mode 100644 index 00000000..9b3c0756 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistDetailsDtoMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistDetailsDtoMapping +{ + /// + /// Converts to . + /// + /// The playlist details data to be converted. + /// The converted response. + public static PlaylistResponse ToResponse(this PlaylistDetailsDto data) + { + return new PlaylistResponse( + data.Playlist.Id, + data.Playlist.Name, + data.Playlist.Description, + data.Playlist.Type, + [.. data.Entries.Select(entry => entry.ToResponse())], + data.Playlist.EntryCount, + data.Playlist.CreatedOnUtc, + data.Playlist.UpdatedOnUtc); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs new file mode 100644 index 00000000..5a34e182 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntityMapping.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this PlaylistEntity repositoryEntity) + { + List entries = []; + // The entries are ordered by their position, because the order of a navigation collection is not guaranteed by the storage medium. + foreach (PlaylistEntryEntity entryEntity in repositoryEntity.Entries.OrderBy(entry => entry.Position)) + { + Result convertEntryResult = entryEntity.ToDomainEntity(); + if (convertEntryResult.IsFailure) + return convertEntryResult.Errors; + entries.Add(convertEntryResult.Value); + } + + return Playlist.Create( + PlaylistId.Create(repositoryEntity.Id), + UserId.Create(repositoryEntity.UserId), + repositoryEntity.Name, + Optional.FromNullable(repositoryEntity.Description), + repositoryEntity.Type, + entries, + repositoryEntity.CreatedOnUtc, + Optional.FromNullable(repositoryEntity.UpdatedOnUtc)); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs new file mode 100644 index 00000000..c6c555f2 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryDtoMapping.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntryDtoMapping +{ + /// + /// Converts to . + /// + /// The playlist entry data to be converted. + /// The converted response. + public static PlaylistEntryResponse ToResponse(this PlaylistEntryDto data) + { + if (data.Display is null) + return new PlaylistEntryResponse( + data.Entry.Id, + data.Entry.MediaItemId, + data.Entry.MediaItemType, + data.DisplayPosition, + Guid.Empty, + Guid.Empty, + Guid.Empty, + string.Empty, + string.Empty, + string.Empty, + 0, + null); + + PlaylistEntryDisplayDto display = data.Display; + return new PlaylistEntryResponse( + data.Entry.Id, + data.Entry.MediaItemId, + data.Entry.MediaItemType, + data.DisplayPosition, + display.LibraryId, + display.AlbumId, + display.ArtistId, + display.TrackTitle, + display.AlbumTitle, + display.ArtistName, + display.DurationInSeconds, + display.CoverPath); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs new file mode 100644 index 00000000..ca1c256c --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryEntityMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntryEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// + /// An containing either a successfully converted , or an error message. + /// + public static Result ToDomainEntity(this PlaylistEntryEntity repositoryEntity) + { + return PlaylistEntry.Create( + PlaylistEntryId.Create(repositoryEntity.Id), + MediaItemId.Create(repositoryEntity.MediaItemId), + repositoryEntity.MediaItemType, + repositoryEntity.Position); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs new file mode 100644 index 00000000..81a82715 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistEntryMapping.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using System; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistEntryMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The Id of the playlist that owns the entry. + /// The converted repository entity. + public static PlaylistEntryEntity ToRepositoryEntity(this PlaylistEntry domainEntity, Guid playlistId) + { + return new PlaylistEntryEntity + { + Id = domainEntity.Id.Value, + PlaylistId = playlistId, + MediaItemId = domainEntity.MediaItemId.Value, + MediaItemType = domainEntity.MediaItemType, + Position = domainEntity.Position + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs new file mode 100644 index 00000000..19c4c591 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistMapping.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using System; +using System.Linq; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistMapping +{ + /// + /// Converts to . + /// + /// The domain entity to be converted. + /// The converted repository entity. + public static PlaylistEntity ToRepositoryEntity(this Playlist domainEntity) + { + return new PlaylistEntity + { + Id = domainEntity.Id.Value, + UserId = domainEntity.UserId.Value, + Name = domainEntity.Name, + Description = domainEntity.Description.HasValue ? domainEntity.Description.Value : null, + Type = domainEntity.Type, + Entries = [.. domainEntity.Entries + .OrderBy(entry => entry.Position) + .Select(entry => entry.ToRepositoryEntity(domainEntity.Id.Value))], + // This is the correct count for an insert. The update path deliberately keeps the stored count, because details edits never load the entries and must not overwrite it. + EntryCount = domainEntity.Entries.Count, + CreatedOnUtc = domainEntity.CreatedOnUtc, + CreatedBy = Guid.Empty, + UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null, + UpdatedBy = null + }; + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs new file mode 100644 index 00000000..d141ca57 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/PlaylistSummaryDtoMapping.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Contracts.Responses.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class PlaylistSummaryDtoMapping +{ + /// + /// Converts to . + /// + /// The data transfer object to be converted. + /// The converted response. + public static PlaylistSummaryResponse ToResponse(this PlaylistSummaryDto dto) + { + return new PlaylistSummaryResponse( + dto.Id, + dto.Name, + dto.Description, + dto.Type, + dto.EntryCount, + dto.CreatedOnUtc, + dto.UpdatedOnUtc); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs new file mode 100644 index 00000000..5d36d529 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Playlists/UpdatePlaylistRequestMapping.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Requests.Playlists; +#endregion + +namespace Lumina.Application.Common.Mapping.Playlists; + +/// +/// Extension methods for converting . +/// +public static class UpdatePlaylistRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The Id of the playlist, taken from the route. + /// The converted command. + public static UpdatePlaylistCommand ToCommand(this UpdatePlaylistRequest request, string? playlistId) + { + return new UpdatePlaylistCommand(playlistId, request.Name, request.Description); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs new file mode 100644 index 00000000..0650403d --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; + +/// +/// Command for adding several tracks to a playlist of the current user, in order. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifiers of the tracks to add, in the order they must take. +[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackCount: {TrackIds.Count}")] +public record AddPlaylistEntriesCommand( + string? PlaylistId, + List? TrackIds +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs new file mode 100644 index 00000000..fdce4262 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandler.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Playlists; +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.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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.Playlists.Commands.AddPlaylistEntries; + +/// +/// Handler for the command to add several tracks to a playlist of the current user, in order. +/// +public class AddPlaylistEntriesCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + 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 to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public AddPlaylistEntriesCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to add several tracks to a playlist of the current user, in order. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the number of appended entries and the playlist activity time, or an error message. + /// + public async Task> HandleAsync(AddPlaylistEntriesCommand 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 identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + + // A missing playlist is reported before any track is read. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The referenced tracks are resolved in a few bounded chunks, grouped by library, so adding a long queue does not turn into one query per entry. + // Duplicate track Ids are collapsed for the lookup, because the same track may legitimately appear more than once in a playlist. + List distinctTrackIds = [.. command.TrackIds!.Distinct()]; + Result getAccessInfoResult = await _unitOfWork.TrackRepository.GetAccessInfoByIdsAsync(distinctTrackIds, cancellationToken).ConfigureAwait(false); + if (getAccessInfoResult.IsFailure) + return getAccessInfoResult.Errors; + if (getAccessInfoResult.Value.TrackCount != distinctTrackIds.Count) + return DomainErrors.Music.TrackNotFound; + + // Every library that owns one of the referenced tracks must be reachable by the current user. The libraries are checked once each, + // so a queue made of many tracks of the same library does not evaluate the policy once per track. + foreach (Guid libraryId in getAccessInfoResult.Value.LibraryIds) + { + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + // A track whose library is not reachable is reported exactly like a missing track, so the response cannot be used to probe whether a track exists in another user's library. + if (!canAccessLibrary) + return DomainErrors.Music.TrackNotFound; + } + + if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack)) + return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems; + + DateTime updatedOnUtc = DateTime.UtcNow; + Result addEntriesResult = await _unitOfWork.PlaylistRepository + .AddEntriesAsync(playlistId, userId, command.TrackIds!, PlaylistMediaItemType.MusicTrack, entryIds: null, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (addEntriesResult.IsFailure) + return addEntriesResult.Errors; + + return new PlaylistEntriesAddedResponse( + playlistId, + addEntriesResult.Value.AddedCount, + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs new file mode 100644 index 00000000..1e3d637f --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidator.cs @@ -0,0 +1,42 @@ +#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.Playlists.Commands.AddPlaylistEntries; + +/// +/// Validates the needed validation rules for . +/// +public class AddPlaylistEntriesCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.TrackIds) + .NotNull() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackIds) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty) + .When(command => command.TrackIds is not null); + + RuleForEach(command => command.TrackIds) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs new file mode 100644 index 00000000..c9afd81c --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; + +/// +/// Command for adding a track to a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifier of the track to add. +[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackId: {TrackId}")] +public record AddPlaylistEntryCommand( + string? PlaylistId, + Guid? TrackId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs new file mode 100644 index 00000000..35f021d5 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandler.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +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.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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.Playlists.Commands.AddPlaylistEntry; + +/// +/// Handler for the command to add a track to a playlist of the current user. +/// +public class AddPlaylistEntryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + 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 to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public AddPlaylistEntryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to add a track to a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the appended entry and the playlist activity time, or an error message. + /// + public async Task> HandleAsync(AddPlaylistEntryCommand 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 identifiers are non-empty Guids before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + Guid trackId = command.TrackId!.Value; + + // A missing playlist is reported before the track is read. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The track must exist, and its library must be reachable by the current user, so another user's library cannot be used as a source. + Result getTrackResult = await _unitOfWork.TrackRepository + .GetByIdAsync(trackId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getTrackResult.IsFailure) + return getTrackResult.Errors; + if (getTrackResult.Value is null) + return DomainErrors.Music.TrackNotFound; + + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(getTrackResult.Value.LibraryId), cancellationToken).ConfigureAwait(false); + // A track whose library is not reachable is reported exactly like a missing track, so the response cannot be used to probe whether a track exists in another user's library. + if (!canAccessLibrary) + return DomainErrors.Music.TrackNotFound; + + if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack)) + return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems; + + Guid entryId = Guid.NewGuid(); + DateTime updatedOnUtc = DateTime.UtcNow; + Result addEntryResult = await _unitOfWork.PlaylistRepository + .AddEntriesAsync(playlistId, userId, [trackId], PlaylistMediaItemType.MusicTrack, [entryId], updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (addEntryResult.IsFailure) + return addEntryResult.Errors; + + // Only the appended entry is read back, with the display details of its track, so a single add does not return the whole playlist. + // The appended entry is the last one, so the read-back derives its display position from the stored entry count. + Result getEntryResult = await _unitOfWork.PlaylistRepository.GetAppendedEntryDetailsForUserAsync(playlistId, userId, entryId, cancellationToken).ConfigureAwait(false); + if (getEntryResult.IsFailure) + return getEntryResult.Errors; + if (getEntryResult.Value is null) + return DomainErrors.Playlists.PlaylistEntryNotFound; + + return new PlaylistEntryAddedResponse( + playlistId, + getEntryResult.Value.ToResponse(), + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs new file mode 100644 index 00000000..fb1e7e57 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidator.cs @@ -0,0 +1,38 @@ +#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.Playlists.Commands.AddPlaylistEntry; + +/// +/// Validates the needed validation rules for . +/// +public class AddPlaylistEntryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .NotNull() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(command => command.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty) + .When(command => command.TrackId is not null); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs new file mode 100644 index 00000000..deee7e4a --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommand.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Command to add every track of a music library, an artist or an album to a playlist, with the track Ids resolved by the server. +/// +/// The Id of the playlist, taken from the route. +/// The Id of the music library the scope belongs to. +/// The Id of the artist the scope is limited to, if applicable. +/// The Id of the album the scope is limited to, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")] +public record AddPlaylistScopeEntriesCommand( + string? PlaylistId, + Guid? LibraryId, + Guid? ArtistId, + Guid? AlbumId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs new file mode 100644 index 00000000..7f169e67 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandler.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +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.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Handler for the command to add every track of a music library, an artist or an album to a playlist. +/// +public class AddPlaylistScopeEntriesCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + 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 to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public AddPlaylistScopeEntriesCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IAuthorizationService authorizationService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the command to add every track of a music library, an artist or an album to a playlist. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the number of appended entries and the playlist activity time, or an error message. + /// + public async Task> HandleAsync(AddPlaylistScopeEntriesCommand 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 identifiers are non-empty Guids before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + Guid libraryId = command.LibraryId!.Value; + + // A missing playlist is reported before a whole library is resolved. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The whole scope belongs to one library, so access is evaluated once for the entire scope. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + if (!Playlist.CanContain(getPlaylistResult.Value.Type, PlaylistMediaItemType.MusicTrack)) + return DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems; + + // The repository resolves the scope and appends it in one set-based statement, so a whole library of any size is appended without + // materializing its track Ids, sorting them in memory, or constructing one domain event per track. + DateTime updatedOnUtc = DateTime.UtcNow; + Result addEntriesResult = await _unitOfWork.PlaylistRepository + .AddScopeEntriesAsync(playlistId, userId, libraryId, command.ArtistId, command.AlbumId, PlaylistMediaItemType.MusicTrack, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (addEntriesResult.IsFailure) + return addEntriesResult.Errors; + + return new PlaylistEntriesAddedResponse( + playlistId, + addEntriesResult.Value.AddedCount, + addEntriesResult.Value.AddedCount == 0 ? null : updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs new file mode 100644 index 00000000..ce9bb13d --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidator.cs @@ -0,0 +1,41 @@ +#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.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Validates the needed validation rules for . +/// +public class AddPlaylistScopeEntriesCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.LibraryId) + .Must(libraryId => libraryId.HasValue && libraryId.Value != Guid.Empty) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(command => command.ArtistId) + .Must(artistId => !artistId.HasValue || artistId.Value != Guid.Empty) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(command => command.AlbumId) + .Must(albumId => !albumId.HasValue || albumId.Value != Guid.Empty) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs new file mode 100644 index 00000000..4be34f54 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommand.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist; + +/// +/// Command for creating a playlist of the current user. +/// +/// The name of the playlist. +/// The optional description of the playlist. +/// The kind of media the playlist holds. +[DebuggerDisplay("Name: {Name}")] +public record CreatePlaylistCommand( + string? Name, + string? Description, + PlaylistType? Type +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs new file mode 100644 index 00000000..bafaa12e --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandHandler.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Queries.GetPlaylist; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +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.Playlists.Commands.CreatePlaylist; + +/// +/// Handler for the command to create a playlist of the current user. +/// +public class CreatePlaylistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + 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 to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public CreatePlaylistCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to create a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the created , or an error message. + /// + public async Task> HandleAsync(CreatePlaylistCommand 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 createPlaylistResult = Playlist.Create( + UserId.Create(userId), + command.Name!, + Optional.FromNullable(command.Description), + command.Type!.Value); + if (createPlaylistResult.IsFailure) + return createPlaylistResult.Errors; + Playlist playlist = createPlaylistResult.Value; + + Result insertResult = await _unitOfWork.PlaylistRepository.InsertAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (insertResult.IsFailure) + return insertResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in playlist.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored. + Result getDetailsResult = await _unitOfWork.PlaylistRepository + .GetDetailsForUserAsync(playlist.Id.Value, userId, 0, PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE, cancellationToken).ConfigureAwait(false); + if (getDetailsResult.IsFailure) + return getDetailsResult.Errors; + if (getDetailsResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + return getDetailsResult.Value.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs new file mode 100644 index 00000000..5f1f8fa6 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidator.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.CreatePlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class CreatePlaylistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistCommandValidator() + { + RuleFor(command => command.Name) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistNameCannotBeEmpty); + + RuleFor(command => command.Name) + .MaximumLength(255) + .WithError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + + RuleFor(command => command.Description) + .MaximumLength(2000) + .WithError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + + RuleFor(command => command.Type) + .NotNull() + .WithError(Errors.Playlists.PlaylistTypeIsInvalid); + + RuleFor(command => command.Type) + .IsInEnum() + .WithError(Errors.Playlists.PlaylistTypeIsInvalid) + .When(command => command.Type is not null); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs new file mode 100644 index 00000000..9d5dfd6e --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommand.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Command for deleting a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +[DebuggerDisplay("PlaylistId: {PlaylistId}")] +public record DeletePlaylistCommand( + string? PlaylistId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs new file mode 100644 index 00000000..0849b509 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandler.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +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.Playlists.Commands.DeletePlaylist; + +/// +/// Handler for the command to delete a playlist of the current user. +/// +public class DeletePlaylistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + 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 to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public DeletePlaylistCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to delete a playlist of the current user. + /// + /// 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(DeletePlaylistCommand 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 identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + + // The playlist is loaded so that its aggregate can raise the deletion event before the row is removed. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + Result toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Playlist playlist = toDomainEntityResult.Value; + + Result deleteResult = playlist.Delete(); + if (deleteResult.IsFailure) + return deleteResult.Errors; + + Result deletePlaylistResult = await _unitOfWork.PlaylistRepository.DeleteByIdAsync(playlist.Id.Value, cancellationToken).ConfigureAwait(false); + if (deletePlaylistResult.IsFailure) + return deletePlaylistResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + foreach (IDomainEvent domainEvent in playlist.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + return Result.Deleted; + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs new file mode 100644 index 00000000..0498533f --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidator.cs @@ -0,0 +1,29 @@ +#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.Playlists.Commands.DeletePlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class DeletePlaylistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs new file mode 100644 index 00000000..6f27d432 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommand.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Command for moving one entry of a playlist of the current user to a new position. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifier of the entry to move, taken from the route. +/// The new zero based position of the entry. +[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}; TargetPosition: {TargetPosition}")] +public record MovePlaylistEntryCommand( + string? PlaylistId, + string? PlaylistEntryId, + int? TargetPosition +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs new file mode 100644 index 00000000..ce82bf08 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandler.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Playlists; +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.Playlists.Commands.MovePlaylistEntry; + +/// +/// Handler for the command to move one entry of a playlist of the current user to a new position. +/// +public class MovePlaylistEntryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + 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 to retrieve the current user information. + /// Injected validator for application validation rules. + public MovePlaylistEntryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to move one entry of a playlist of the current user to a new position. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the moved entry and its position, or an error message. + /// + public async Task> HandleAsync(MovePlaylistEntryCommand 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 playlistId = Guid.Parse(command.PlaylistId!); + Guid playlistEntryId = Guid.Parse(command.PlaylistEntryId!); + int targetPosition = command.TargetPosition!.Value; + + // The entry is moved directly in the storage medium, so a playlist of any size is not loaded into memory for one move. + DateTime updatedOnUtc = DateTime.UtcNow; + Result moveEntryResult = await _unitOfWork.PlaylistRepository + .MoveEntryAsync(playlistId, userId, playlistEntryId, targetPosition, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (moveEntryResult.IsFailure) + return moveEntryResult.Errors; + + return new PlaylistEntryMovedResponse( + playlistId, + playlistEntryId, + targetPosition, + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs new file mode 100644 index 00000000..afa6ca29 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidator.cs @@ -0,0 +1,47 @@ +#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.Playlists.Commands.MovePlaylistEntry; + +/// +/// Validates the needed validation rules for . +/// +public class MovePlaylistEntryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .Must(entryId => Guid.TryParse(entryId, out Guid parsedEntryId) && parsedEntryId != Guid.Empty) + .When(command => command.PlaylistEntryId is not null && command.PlaylistEntryId.Length > 0) + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + + RuleFor(command => command.TargetPosition) + .NotNull() + .WithError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + + RuleFor(command => command.TargetPosition) + .Must(targetPosition => targetPosition.HasValue && targetPosition.Value >= 0) + .When(command => command.TargetPosition.HasValue) + .WithError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs new file mode 100644 index 00000000..99ab3010 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Command for removing an entry from a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +/// The unique identifier of the entry to remove, taken from the route. +[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}")] +public record RemovePlaylistEntryCommand( + string? PlaylistId, + string? PlaylistEntryId +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs new file mode 100644 index 00000000..e317f787 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandler.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Contracts.Responses.Playlists; +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.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Handler for the command to remove an entry from a playlist of the current user. +/// +public class RemovePlaylistEntryCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + 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 to retrieve the current user information. + /// Injected validator for application validation rules. + public RemovePlaylistEntryCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _validator = validator; + } + + /// + /// Handles the command to remove an entry from a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the removed entry with zero repositioned entries, or an error message. + /// + public async Task> HandleAsync(RemovePlaylistEntryCommand 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 playlistId = Guid.Parse(command.PlaylistId!); + Guid playlistEntryId = Guid.Parse(command.PlaylistEntryId!); + + // The row is deleted and the gap is closed in set-based statements, so a playlist of any size is not loaded into memory for one removal. + DateTime updatedOnUtc = DateTime.UtcNow; + Result removeEntryResult = await _unitOfWork.PlaylistRepository.RemoveEntryAsync(playlistId, userId, playlistEntryId, updatedOnUtc, cancellationToken).ConfigureAwait(false); + if (removeEntryResult.IsFailure) + return removeEntryResult.Errors; + + return new PlaylistEntryRemovedResponse( + playlistId, + playlistEntryId, + removeEntryResult.Value, + updatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs new file mode 100644 index 00000000..ffcaf9eb --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidator.cs @@ -0,0 +1,38 @@ +#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.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Validates the needed validation rules for . +/// +public class RemovePlaylistEntryCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + + RuleFor(command => command.PlaylistEntryId) + .Must(entryId => Guid.TryParse(entryId, out Guid parsedEntryId) && parsedEntryId != Guid.Empty) + .When(command => command.PlaylistEntryId is not null && command.PlaylistEntryId.Length > 0) + .WithError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs new file mode 100644 index 00000000..f7a8bfbb --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommand.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Command for updating the details of a playlist of the current user. +/// +/// The unique identifier of the playlist, taken from the route. +/// The name of the playlist. +/// The optional description of the playlist. +[DebuggerDisplay("PlaylistId: {PlaylistId}")] +public record UpdatePlaylistCommand( + string? PlaylistId, + string? Name, + string? Description +) : ICommand; diff --git a/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs new file mode 100644 index 00000000..0e353107 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandler.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +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.Playlists.Commands.UpdatePlaylist; + +/// +/// Handler for the command to update the details of a playlist of the current user. +/// +public class UpdatePlaylistCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IDomainEventsQueue _domainEventsQueue; + 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 to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected validator for application validation rules. + public UpdatePlaylistCommandHandler( + IUnitOfWork unitOfWork, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _validator = validator; + } + + /// + /// Handles the command to update the details of a playlist of the current user. + /// + /// The command to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the updated , or an error message. + /// + public async Task> HandleAsync(UpdatePlaylistCommand 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 identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(command.PlaylistId!); + + // The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetByIdForUserAsync(playlistId, userId, shouldIncludeNavigationProperties: false, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + Result toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + Playlist playlist = toDomainEntityResult.Value; + + Result updateDetailsResult = playlist.UpdateDetails(command.Name!, Optional.FromNullable(command.Description)); + if (updateDetailsResult.IsFailure) + return updateDetailsResult.Errors; + + Result updateResult = await _unitOfWork.PlaylistRepository.UpdateAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + return saveChangesResult.Errors; + + foreach (IDomainEvent domainEvent in playlist.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // A details update only changes the playlist scalars, so the response carries those scalars and the audit timestamp the interceptor actually stored. + return new PlaylistDetailsResponse( + playlist.Id.Value, + playlist.Name, + playlist.Description.HasValue ? playlist.Description.Value : null, + playlist.Type, + getPlaylistResult.Value.UpdatedOnUtc); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs new file mode 100644 index 00000000..50f7fa16 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidator.cs @@ -0,0 +1,41 @@ +#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.Playlists.Commands.UpdatePlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class UpdatePlaylistCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistCommandValidator() + { + RuleFor(command => command.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(command => command.PlaylistId is not null && command.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(command => command.Name) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistNameCannotBeEmpty); + + RuleFor(command => command.Name) + .MaximumLength(255) + .WithError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + + RuleFor(command => command.Description) + .MaximumLength(2000) + .WithError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs new file mode 100644 index 00000000..8cfc66e3 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQuery.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist; + +/// +/// Query for getting a playlist of the current user, together with a window of its ordered entries. +/// +/// The unique identifier of the playlist, taken from the route. +/// The zero based position of the first entry to return. +/// The maximum number of entries to return in this window. +[DebuggerDisplay("PlaylistId: {PlaylistId}; Offset: {Offset}; Limit: {Limit}")] +public record GetPlaylistQuery( + string? PlaylistId, + int Offset = 0, + int Limit = PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE +) : IQuery; diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs new file mode 100644 index 00000000..553b7121 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryHandler.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +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.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist; + +/// +/// Handler for the query to get a playlist of the current user, together with its ordered entries. +/// +public class GetPlaylistQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + private readonly IAuthorizationService _authorizationService; + 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 to retrieve the current user information. + /// Injected service for authorization related functionality. + /// Injected validator for application validation rules. + public GetPlaylistQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator validator) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + _authorizationService = authorizationService; + _validator = validator; + } + + /// + /// Handles the query to get a playlist of the current user, together with its ordered entries. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the requested , or an error message. + /// + public async Task> HandleAsync(GetPlaylistQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifier is a non-empty Guid before this point. + Guid playlistId = Guid.Parse(query.PlaylistId!); + + // The playlist is scoped to the current user by the repository, so a playlist of another user is indistinguishable from a missing one. + Result getPlaylistResult = await _unitOfWork.PlaylistRepository + .GetDetailsForUserAsync(playlistId, userId, query.Offset, query.Limit, cancellationToken).ConfigureAwait(false); + if (getPlaylistResult.IsFailure) + return getPlaylistResult.Errors; + if (getPlaylistResult.Value is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // Check the access permissions for each library that the tracks in the playlist might belong to. + PlaylistDetailsDto playlist = getPlaylistResult.Value; + List libraryIds = [.. playlist.Entries + .Select(entry => entry.Display?.LibraryId ?? Guid.Empty) + .Where(libraryId => libraryId != Guid.Empty) + .Distinct()]; + Dictionary libraryAccess = []; + foreach (Guid libraryId in libraryIds) + { + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + libraryAccess[libraryId] = canAccessLibrary; + } + + if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary)) + { + List entries = []; + foreach (PlaylistEntryDto entry in playlist.Entries) + { + Guid libraryId = entry.Display?.LibraryId ?? Guid.Empty; + if (libraryId == Guid.Empty || libraryAccess[libraryId]) + entries.Add(entry); + else + // Keep the row so its owner can see and remove it, but do not expose display data from a library the user cannot access. + entries.Add(entry with { Display = null }); + } + playlist = playlist with { Entries = entries }; + } + + return playlist.ToResponse(); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs new file mode 100644 index 00000000..528e64a9 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/GetPlaylistQueryValidator.cs @@ -0,0 +1,37 @@ +#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.Playlists.Queries.GetPlaylist; + +/// +/// Validates the needed validation rules for . +/// +public class GetPlaylistQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistQueryValidator() + { + RuleFor(query => query.PlaylistId) + .NotEmpty() + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(query => query.PlaylistId) + .Must(playlistId => Guid.TryParse(playlistId, out Guid parsedPlaylistId) && parsedPlaylistId != Guid.Empty) + .When(query => query.PlaylistId is not null && query.PlaylistId.Length > 0) + .WithError(Errors.Playlists.PlaylistIdCannotBeEmpty); + + RuleFor(query => query.Offset) + .GreaterThanOrEqualTo(0) + .WithError(Errors.Playlists.PlaylistEntryWindowOffsetIsInvalid); + + RuleFor(query => query.Limit) + .InclusiveBetween(1, PlaylistWindow.MAXIMUM_ENTRY_WINDOW_SIZE) + .WithError(Errors.Playlists.PlaylistEntryWindowLimitIsInvalid); + } +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/PlaylistWindow.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/PlaylistWindow.cs new file mode 100644 index 00000000..8f8f1806 --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylist/PlaylistWindow.cs @@ -0,0 +1,17 @@ +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist; + +/// +/// The bounds of one playlist entry read window. +/// +public static class PlaylistWindow +{ + /// + /// The default number of entries a single read window returns. + /// + public const int DEFAULT_ENTRY_WINDOW_SIZE = 200; + + /// + /// The maximum number of entries a single read window may return. + /// + public const int MAXIMUM_ENTRY_WINDOW_SIZE = 1000; +} diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs new file mode 100644 index 00000000..8901463f --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQuery.cs @@ -0,0 +1,10 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists; + +/// +/// Query for getting the playlists of the current user. +/// +public record GetPlaylistsQuery : IQuery; diff --git a/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs new file mode 100644 index 00000000..7b55808e --- /dev/null +++ b/src/Lumina.Application/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandler.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists; + +/// +/// Handler for the query to get the playlists of the current user. +/// +public class GetPlaylistsQueryHandler : IQueryHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly ICurrentUserService _currentUserService; + + /// + /// Initializes a new instance of the class. + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service to retrieve the current user information. + public GetPlaylistsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService) + { + _unitOfWork = unitOfWork; + _currentUserService = currentUserService; + } + + /// + /// Handles the query to get the playlists of the current user. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlists of the current user, or an error message. + /// + public async Task> HandleAsync(GetPlaylistsQuery query, CancellationToken cancellationToken) + { + // 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> getPlaylistsResult = await _unitOfWork.PlaylistRepository.GetAllForUserAsync(userId, cancellationToken).ConfigureAwait(false); + if (getPlaylistsResult.IsFailure) + return getPlaylistsResult.Errors; + + return Result.From(getPlaylistsResult.Value.Select(playlist => playlist.ToResponse()).ToArray()); + } +} diff --git a/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs new file mode 100644 index 00000000..84d5dcd1 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntriesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for adding several tracks to a playlist of the current user, in order. +/// +/// The Ids of the tracks to add, in the order they must take. Required. +[DebuggerDisplay("TrackCount: {TrackIds.Count}")] +public record AddPlaylistEntriesRequest( + List? TrackIds +); diff --git a/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs new file mode 100644 index 00000000..dbc52982 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistEntryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for adding a track to a playlist of the current user. +/// +/// The Id of the track to add. Required. +[DebuggerDisplay("TrackId: {TrackId}")] +public record AddPlaylistEntryRequest( + Guid? TrackId +); diff --git a/src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs new file mode 100644 index 00000000..6d040899 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request to add every track of a music library, an artist or an album to a playlist, resolved on the server. +/// +/// The Id of the music library the scope belongs to. Required. +/// The Id of the artist the scope is limited to. Optional. +/// The Id of the album the scope is limited to. Optional. +[DebuggerDisplay("LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")] +public record AddPlaylistScopeEntriesRequest( + Guid LibraryId, + Guid? ArtistId = null, + Guid? AlbumId = null +); diff --git a/src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs b/src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs new file mode 100644 index 00000000..a929ee46 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/CreatePlaylistRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for creating a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +/// The kind of media the playlist holds. Required. +[DebuggerDisplay("Name: {Name}")] +public record CreatePlaylistRequest( + string? Name, + string? Description, + PlaylistType? Type +); diff --git a/src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs b/src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs new file mode 100644 index 00000000..c167abf0 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/GetPlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for getting a window of the entries of a playlist of the current user. +/// +/// The zero based position of the first entry to return. Optional; defaults to 0. +/// The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200. +[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")] +public record GetPlaylistRequest( + int? Offset, + int? Limit +); diff --git a/src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs b/src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs new file mode 100644 index 00000000..dd8e06ee --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/MovePlaylistEntryRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for moving one entry of a playlist of the current user to a new position. +/// +/// The new zero based position of the entry. Required. +[DebuggerDisplay("TargetPosition: {TargetPosition}")] +public record MovePlaylistEntryRequest( + int? TargetPosition +); diff --git a/src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs b/src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs new file mode 100644 index 00000000..277abc0d --- /dev/null +++ b/src/Lumina.Contracts/Requests/Playlists/UpdatePlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Playlists; + +/// +/// Represents a request for updating the details of a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +[DebuggerDisplay("Name: {Name}")] +public record UpdatePlaylistRequest( + string? Name, + string? Description +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs new file mode 100644 index 00000000..0f2e9838 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistDetailsResponse.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the editable scalars of a playlist after a details update. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}")] +public sealed record PlaylistDetailsResponse( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs new file mode 100644 index 00000000..b0989579 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntriesAddedResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the result of appending several tracks to a playlist, without returning the whole playlist. +/// +/// The Id of the playlist the entries were added to. +/// The number of entries that were appended, including repeated tracks. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; AddedCount: {AddedCount}")] +public sealed record PlaylistEntriesAddedResponse( + Guid PlaylistId, + int AddedCount, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs new file mode 100644 index 00000000..391029d5 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryAddedResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the entry that was appended to a playlist, together with its playlist and the new activity time of the playlist. +/// +/// The Id of the playlist the entry was added to. +/// The added entry, with the display details of the media item it references. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; Entry: {Entry.Id}")] +public sealed record PlaylistEntryAddedResponse( + Guid PlaylistId, + PlaylistEntryResponse Entry, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs new file mode 100644 index 00000000..c3f758c3 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryMovedResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the result of moving one entry of a playlist to a new position. +/// +/// The Id of the playlist whose entry was moved. +/// The Id of the moved entry. +/// The new zero based position of the entry. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; EntryId: {EntryId}; Position: {Position}")] +public sealed record PlaylistEntryMovedResponse( + Guid PlaylistId, + Guid EntryId, + int Position, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs new file mode 100644 index 00000000..ca07a0d8 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryRemovedResponse.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for the result of removing an entry from a playlist. +/// +/// The Id of the playlist the entry was removed from. +/// The Id of the removed entry. +/// Always zero, because sparse order keys need no remaining entries to be repositioned. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; RemovedEntryId: {RemovedEntryId}; RepositionedCount: {RepositionedCount}")] +public sealed record PlaylistEntryRemovedResponse( + Guid PlaylistId, + Guid RemovedEntryId, + int RepositionedCount, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs new file mode 100644 index 00000000..46f5add3 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistEntryResponse.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for an ordered entry of a playlist. +/// +/// The Id of the entry. +/// The Id of the media item referenced by the entry. +/// The kind of media item referenced by the entry. +/// The zero based position of the entry in the playlist. +/// The Id of the media library that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the collection that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the creator of the media item, or an empty Guid when the item no longer exists. +/// The title of the media item, or an empty string when the item no longer exists. +/// The title of the collection that contains the media item, or an empty string when the item no longer exists. +/// The name of the creator of the media item, or an empty string when the item no longer exists. +/// The duration of the media item in seconds, or zero when the item no longer exists. +/// The path of the cover art of the collection, if available. +[DebuggerDisplay("MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")] +public sealed record PlaylistEntryResponse( + Guid Id, + Guid MediaItemId, + PlaylistMediaItemType MediaItemType, + int Position, + Guid LibraryId, + Guid CollectionId, + Guid CreatorId, + string MediaItemTitle, + string CollectionTitle, + string CreatorName, + int DurationInSeconds, + string? CoverPath +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs new file mode 100644 index 00000000..7fd2a7dd --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistResponse.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for a playlist together with its ordered entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The ordered entries of the requested window of the playlist. +/// The number of entries the playlist holds, even when only a window of them is returned. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}; Window: {Entries.Count}")] +public sealed record PlaylistResponse( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + IReadOnlyList Entries, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs b/src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs new file mode 100644 index 00000000..d6a089f1 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Playlists/PlaylistSummaryResponse.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Responses.Playlists; + +/// +/// Represents a response for a playlist in a list, without its entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")] +public sealed record PlaylistSummaryResponse( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs new file mode 100644 index 00000000..b9fb14eb --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/PlaylistConfiguration.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class PlaylistConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("Playlists"); + builder.HasKey(playlist => playlist.Id); + builder.Property(playlist => playlist.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); + + // A playlist belongs to the user that created it, and it is removed with that user. + builder.HasOne() + .WithMany() + .HasForeignKey(playlist => playlist.UserId) + .IsRequired() + .OnDelete(DeleteBehavior.Cascade); + + builder.Property(playlist => playlist.UserId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(playlist => playlist.Name) + .IsRequired() + .HasMaxLength(255) + .HasColumnOrder(2); + + builder.Property(playlist => playlist.Description) + .HasMaxLength(2000) + .HasColumnOrder(3); + + builder.Property(playlist => playlist.Type) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(4); + + // Audit. + builder.Property(playlist => playlist.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(playlist => playlist.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(playlist => playlist.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(playlist => playlist.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + // The entry count is maintained by the set-based entry operations, so a window read never counts the entries of the whole playlist. + builder.Property(playlist => playlist.EntryCount) + .IsRequired() + .HasDefaultValue(0) + .HasColumnOrder(10); + + // The concurrency token is incremented by every details edit and by every set-based entry operation, so a concurrent writer is + // detected instead of silently overwriting the ordering work of another request. + builder.Property(playlist => playlist.Version) + .IsConcurrencyToken() + .HasDefaultValue(0L) + .HasColumnOrder(9); + + // The entries of the playlist are owned by the playlist: they are removed with it, and they are never referenced from elsewhere. + builder.HasMany(playlist => playlist.Entries) + .WithOne() + .HasForeignKey(entry => entry.PlaylistId) + .OnDelete(DeleteBehavior.Cascade); + + // Enables the list of the playlists of a user in the order of their most recent activity. + builder.HasIndex(playlist => new { playlist.UserId, playlist.UpdatedOnUtc }); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs new file mode 100644 index 00000000..0b7251e8 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/PlaylistEntryConfiguration.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class PlaylistEntryConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("PlaylistEntries"); + builder.HasKey(entry => entry.Id); + builder.Property(entry => entry.Id) + .ValueGeneratedNever() + .HasColumnOrder(0); + + builder.Property(entry => entry.PlaylistId) + .IsRequired() + .HasColumnOrder(1); + + builder.Property(entry => entry.MediaItemId) + .IsRequired() + .HasColumnOrder(2); + + builder.Property(entry => entry.MediaItemType) + .IsRequired() + .HasConversion() + .HasMaxLength(20) + .HasColumnOrder(3); + + builder.Property(entry => entry.Position) + .IsRequired() + .HasColumnOrder(4); + + // Audit. + builder.Property(entry => entry.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(entry => entry.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(entry => entry.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(entry => entry.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + // The referenced media item is kept by Id only, without a foreign key, so a playlist entry survives the deletion of the item it + // references and its owner can still see and remove the dangling entry. + // The unique index makes the storage medium the owner of the ordering invariant: a duplicate position is rejected even if an operation bypasses the repository. + builder.HasIndex(entry => new { entry.PlaylistId, entry.Position }) + .IsUnique(); + + // Enables finding the playlists that reference a media item, for example when a track is deleted. + builder.HasIndex(entry => entry.MediaItemId); + } +} diff --git a/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs b/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs index 63ac7047..097367c8 100644 --- a/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs +++ b/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs @@ -10,20 +10,21 @@ namespace Lumina.DataAccess.Common.Dapper; /// Maps values to and from the TEXT representation used by the SQLite provider. /// /// -/// The SQLite provider stores columns as TEXT, and Dapper falls back to Convert.ChangeType when materializing such -/// columns into properties. has no string , so that conversion throws -/// an ; this handler performs the conversion explicitly instead. +/// The SQLite provider stores columns as upper case TEXT. Dapper falls back to Convert.ChangeType when materializing +/// such columns into properties. has no string , so that conversion +/// throws an ; this handler performs the conversion explicitly instead, and writes the same upper case +/// representation so raw key comparisons and foreign keys match the rows created by Entity Framework. /// internal sealed class SqliteGuidTypeHandler : SqlMapper.TypeHandler { /// - /// Sets the parameter value to the TEXT representation of the value, keeping writes consistent with reads. + /// Sets the parameter value to the upper case TEXT representation the SQLite provider uses for columns. /// /// The database parameter to set. /// The value to store. public override void SetValue(IDbDataParameter parameter, Guid value) { - parameter.Value = value.ToString(); + parameter.Value = value.ToString().ToUpperInvariant(); } /// diff --git a/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs new file mode 100644 index 00000000..fba99e07 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.Designer.cs @@ -0,0 +1,3673 @@ +// +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("20261021090430_AddsPlaylists")] + partial class AddsPlaylists + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("AlbumGenres", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("AlbumGenres", (string)null); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.Property("AlbumId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("AlbumId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("AlbumTags", (string)null); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("ArtistGenres", (string)null); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.Property("ArtistId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("ArtistId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("ArtistTags", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Biography") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("DateOfBirth") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("DateOfDeath") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1) + .UseCollation("NOCASE"); + + b.Property("LegalName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.HasKey("Id"); + + b.HasIndex("DisplayName") + .IsUnique(); + + b.ToTable("MediaContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("AlbumId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("AlbumContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Barcode") + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Label") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaFormat") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(36); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Packaging") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ReleaseStatus") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("ReleaseTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TotalDiscs") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("TotalTracks") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.HasKey("Id"); + + b.HasIndex("ArtistId", "Title"); + + b.HasIndex("LibraryId", "Title"); + + b.ToTable("Albums", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("ArtistId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("ArtistContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Country") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("Gender") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("IsEnded") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("LifeSpanBegin") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("LifeSpanEnd") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(17); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Type") + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("Website") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "Name") + .IsUnique(); + + b.ToTable("Artists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("OwnerId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("OwnerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("OwnerType", "OwnerId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("MusicArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicLibraryScanItemMetadataEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("ArtistName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(31); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryScanId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.PrimitiveCollection("Moods") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(30); + + b.Property("MusicBrainzArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("MusicBrainzReleaseArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("MusicBrainzReleaseGroupId") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("MusicBrainzReleaseId") + .HasColumnType("TEXT") + .HasColumnOrder(20); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReleaseName") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("ReleaseType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("ReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(28); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(29); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(26); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(27); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("TrackTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.HasKey("Id"); + + b.HasIndex("LibraryScanId", "Path") + .IsUnique(); + + b.ToTable("MusicLibraryScanItemMetadata", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("ArtistId") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("EndedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("LastPositionMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ListenedDurationMilliseconds") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.HasKey("Id"); + + b.HasIndex("TrackId"); + + b.HasIndex("UserId", "CreatedOnUtc"); + + b.ToTable("MusicPlayRecords", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TrackId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("TrackId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("TrackContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("AcoustId") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(44); + + b.Property("AlbumId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("AudioCodec") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("BitDepth") + .HasColumnType("INTEGER") + .HasColumnOrder(23); + + b.Property("Bitrate") + .HasColumnType("INTEGER") + .HasColumnOrder(25); + + b.Property("Bpm") + .HasColumnType("INTEGER") + .HasColumnOrder(30); + + b.Property("Channels") + .HasColumnType("INTEGER") + .HasColumnOrder(22); + + b.Property("Container") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(49); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Disambiguation") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("DiscNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(27); + + b.Property("DurationInSeconds") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsVideo") + .HasColumnType("INTEGER") + .HasColumnOrder(31); + + b.Property("Key") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(42); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(43); + + b.Property("MetadataStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasDefaultValue("Pending") + .HasColumnOrder(41); + + b.Property("MusicBrainzRecordingId") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("MusicBrainzTrackId") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("MusicBrainzWorkId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(17); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("ReplayGainAlbumGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(47); + + b.Property("ReplayGainAlbumPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(48); + + b.Property("ReplayGainTrackGain") + .HasColumnType("decimal(8,2)") + .HasColumnOrder(45); + + b.Property("ReplayGainTrackPeak") + .HasColumnType("decimal(8,6)") + .HasColumnOrder(46); + + b.Property("SampleRate") + .HasColumnType("INTEGER") + .HasColumnOrder(21); + + b.Property("Script") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("TrackNumber") + .HasColumnType("INTEGER") + .HasColumnOrder(26); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("WorkTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("WorkType") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.HasKey("Id"); + + b.HasIndex("AlbumId", "TrackNumber"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Tracks", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MetadataProvidersConfigurationFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("PathTemplateFingerprint") + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ArtworkType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("FileName") + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LastUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Ordinal") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Provider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.HasKey("Id"); + + b.HasIndex("Status"); + + b.HasIndex("BookId", "ArtworkType", "Ordinal") + .IsUnique(); + + b.ToTable("BookArtwork", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("BookId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("MediaContributorId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Role") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.HasKey("Id"); + + b.HasIndex("MediaContributorId"); + + b.HasIndex("BookId", "MediaContributorId", "Role") + .IsUnique(); + + b.ToTable("BookContributors", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasMaxLength(2) + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path") + .IsUnique(); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (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("IsGaplessPlaybackEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(16); + + b.Property("IsMuted") + .HasColumnType("INTEGER") + .HasColumnOrder(20); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ReplayGainMode") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("ShouldAggregateArtworkWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(13); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldAutoplay") + .HasColumnType("INTEGER") + .HasColumnOrder(15); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("ShouldKeepDownloadingWhilePaused") + .HasColumnType("INTEGER") + .HasColumnOrder(14); + + b.Property("ShouldPreserveBookStyles") + .HasColumnType("INTEGER") + .HasColumnOrder(12); + + b.Property("ShouldRenderPdfAsImages") + .HasColumnType("INTEGER") + .HasColumnOrder(11); + + b.Property("StreamingQuality") + .HasColumnType("INTEGER") + .HasColumnOrder(18); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Volume") + .HasColumnType("REAL") + .HasColumnOrder(19); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("TrackGenres", (string)null); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.Property("TrackId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("TrackId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("TrackTags", (string)null); + }); + + modelBuilder.Entity("AlbumGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AlbumTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany() + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ArtistTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany() + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null) + .WithMany("Contributors") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", "Artist") + .WithMany("Albums") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumCatalogNumberEntity", "CatalogNumbers", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("CatalogNumber") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumCatalogNumbers", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumReleaseTypeEntity", "ReleaseTypes", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("AlbumId") + .HasColumnType("TEXT"); + + b1.Property("ReleaseType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("AlbumId"); + + b1.ToTable("AlbumReleaseTypes", (string)null); + + b1.WithOwner() + .HasForeignKey("AlbumId"); + }); + + b.Navigation("Artist"); + + b.Navigation("CatalogNumbers"); + + b.Navigation("Ratings"); + + b.Navigation("ReleaseTypes"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", null) + .WithMany("Contributors") + .HasForeignKey("ArtistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "Area", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("Area") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "BeginArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("BeginArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicAreaEntity", "EndArea", b1 => + { + b1.Property("ArtistEntityId"); + + b1.Property("Disambiguation"); + + b1.Property("Iso3166Code"); + + b1.Property("MusicBrainzAreaId"); + + b1.Property("Name") + .IsRequired(); + + b1.Property("SortName"); + + b1.Property("Type"); + + b1.HasKey("ArtistEntityId"); + + b1.ToTable("Artists"); + + b1 + .ToJson("EndArea") + .HasColumnType("TEXT"); + + b1.WithOwner() + .HasForeignKey("ArtistEntityId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistAliasEntity", "Aliases", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("BeginDate") + .HasColumnType("TEXT"); + + b1.Property("EndDate") + .HasColumnType("TEXT"); + + b1.Property("IsEnded") + .HasColumnType("INTEGER"); + + b1.Property("IsPrimary") + .HasColumnType("INTEGER"); + + b1.Property("Locale") + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("SortName") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b1.Property("Type") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistAliases", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIpiEntity", "Ipis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIpis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistIsniEntity", "Isnis", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("ArtistId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("ArtistId"); + + b1.ToTable("ArtistIsnis", (string)null); + + b1.WithOwner() + .HasForeignKey("ArtistId"); + }); + + b.Navigation("Aliases"); + + b.Navigation("Area"); + + b.Navigation("BeginArea"); + + b.Navigation("EndArea"); + + b.Navigation("Ipis"); + + b.Navigation("Isnis"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany("Contributors") + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", "Album") + .WithMany("Tracks") + .HasForeignKey("AlbumId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AudioRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackIsrcEntity", "Isrcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnName("ISRC"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackIsrcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackMoodEntity", "Moods", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackMoods", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkIswcEntity", "WorkIswcs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkIswcs", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackWorkLanguageEntity", "WorkLanguages", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LanguageCode") + .IsRequired() + .HasMaxLength(5) + .HasColumnType("TEXT"); + + b1.Property("LanguageName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("NativeName") + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b1.Property("TrackId") + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("TrackId"); + + b1.ToTable("TrackWorkLanguages", (string)null); + + b1.WithOwner() + .HasForeignKey("TrackId"); + }); + + b.Navigation("Album"); + + b.Navigation("Isrcs"); + + b.Navigation("Moods"); + + b.Navigation("Ratings"); + + b.Navigation("WorkIswcs"); + + b.Navigation("WorkLanguages"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryPathTemplatePartEntity", "PathTemplateParts", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("IsOptional") + .HasColumnType("INTEGER"); + + b1.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Position") + .HasColumnType("INTEGER") + .HasColumnName("Position"); + + b1.Property("Representation") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId", "Position") + .IsUnique(); + + b1.ToTable("LibraryPathTemplateParts", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("PathTemplateParts"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookArtworkEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Artwork") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookContributorEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany("Contributors") + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("TrackTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", null) + .WithMany() + .HasForeignKey("TrackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", b => + { + b.Navigation("Contributors"); + + b.Navigation("Tracks"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.ArtistEntity", b => + { + b.Navigation("Albums"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackEntity", b => + { + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Navigation("Artwork"); + + b.Navigation("Contributors"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + + 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/20261021090430_AddsPlaylists.cs b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.cs new file mode 100644 index 00000000..42ad1c87 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20261021090430_AddsPlaylists.cs @@ -0,0 +1,93 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsPlaylists : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Playlists", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 255, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 2000, nullable: true), + Type = table.Column(type: "TEXT", maxLength: 20, 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), + Version = table.Column(type: "INTEGER", nullable: false, defaultValue: 0L), + EntryCount = table.Column(type: "INTEGER", nullable: false, defaultValue: 0) + }, + constraints: table => + { + table.PrimaryKey("PK_Playlists", x => x.Id); + table.ForeignKey( + name: "FK_Playlists_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "PlaylistEntries", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + PlaylistId = table.Column(type: "TEXT", nullable: false), + MediaItemId = table.Column(type: "TEXT", nullable: false), + MediaItemType = table.Column(type: "TEXT", maxLength: 20, nullable: false), + Position = table.Column(type: "INTEGER", 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_PlaylistEntries", x => x.Id); + table.ForeignKey( + name: "FK_PlaylistEntries_Playlists_PlaylistId", + column: x => x.PlaylistId, + principalTable: "Playlists", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_PlaylistEntries_MediaItemId", + table: "PlaylistEntries", + column: "MediaItemId"); + + migrationBuilder.CreateIndex( + name: "IX_PlaylistEntries_PlaylistId_Position", + table: "PlaylistEntries", + columns: new[] { "PlaylistId", "Position" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Playlists_UserId_UpdatedOnUtc", + table: "Playlists", + columns: new[] { "UserId", "UpdatedOnUtc" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PlaylistEntries"); + + migrationBuilder.DropTable( + name: "Playlists"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 369efaca..77f187c1 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -1904,6 +1904,119 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Books", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("EntryCount") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0) + .HasColumnOrder(10); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Type") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(0L) + .HasColumnOrder(9); + + b.HasKey("Id"); + + b.HasIndex("UserId", "UpdatedOnUtc"); + + b.ToTable("Playlists", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("MediaItemId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("MediaItemType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PlaylistId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Position") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("MediaItemId"); + + b.HasIndex("PlaylistId", "Position") + .IsUnique(); + + b.ToTable("PlaylistEntries", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => { b.Property("Id") @@ -3429,6 +3542,24 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Ratings"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", null) + .WithMany("Entries") + .HasForeignKey("PlaylistId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => { b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) @@ -3518,6 +3649,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Navigation("Contributors"); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Playlists.PlaylistEntity", b => + { + b.Navigation("Entries"); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => { b.Navigation("Libraries"); diff --git a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs index 3fa99b6b..4bf9642b 100644 --- a/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs +++ b/src/Lumina.DataAccess/Common/Persistence/CollectionReconciler.cs @@ -16,8 +16,9 @@ internal static class CollectionReconciler /// /// /// Existing items that are absent from the desired set are removed, desired items that are absent are added, and matched items are left untouched, unless - /// reports that their non-key values changed, in which case only that item is replaced. Because the tracked instances are - /// never rebuilt as a whole, the rows that did not change keep their identity and their audit columns. + /// reports that their non-key values changed, in which case only that item is replaced, or is + /// provided, in which case the matched tracked item is updated in place. Because the tracked instances are never rebuilt as a whole, the rows that did not change + /// keep their identity and their audit columns. /// /// The type of the tracked items. /// The type of the desired items. @@ -28,13 +29,15 @@ internal static class CollectionReconciler /// Selects the matching key of a desired item. /// Determines whether a matched tracked item must be replaced, because a non-key value changed. /// Creates the entity used for a desired item that is not matched by any tracked item. + /// Applies the incoming non-key values onto a matched tracked item, when the caller updates matched items in place instead of replacing them. public static void Reconcile( ICollection existingItems, IEnumerable incomingItems, Func existingKeySelector, Func incomingKeySelector, Func shouldReplace, - Func createNew) + Func createNew, + Action? applyMatched = null) where TExisting : class where TKey : notnull { @@ -65,6 +68,10 @@ internal static class CollectionReconciler existingItems.Add(replacementItem); existingByKey[incomingKey] = replacementItem; } + else if (applyMatched is not null) + // The caller updates the matched instance in place. This keeps the tracked instance and its key, which is the only + // safe option when the key is user-assigned and the tracked instance is still in the change tracker. + applyMatched(matchedItem, incomingItem); } else { diff --git a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs index 915e921b..15e56d0a 100644 --- a/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs +++ b/src/Lumina.DataAccess/Common/Persistence/EditableValuesCopier.cs @@ -47,7 +47,13 @@ internal static class EditableValuesCopier { if (excludedProperties.Contains(property.Name)) continue; - trackedEntry.Property(property.Name).CurrentValue = incomingEntry.Property(property.Name).CurrentValue; + PropertyEntry trackedProperty = trackedEntry.Property(property.Name); + object? incomingValue = incomingEntry.Property(property.Name).CurrentValue; + // Only an actual change is assigned and marked modified. Assigning every value unconditionally, or relying on change detection that has not run yet, would make the caller unable to tell a no-op save from a real edit. + if (Equals(trackedProperty.CurrentValue, incomingValue)) + continue; + trackedProperty.CurrentValue = incomingValue; + trackedProperty.IsModified = true; } } } diff --git a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs index 9269db51..c01377ea 100644 --- a/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/BookLibrary/BookRepository.cs @@ -226,16 +226,14 @@ internal sealed class BookRepository : IBookRepository // Apply sorting based on the specified sortBy and sortOrder parameters. booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); - IQueryable liteRowsQuery = booksQuery.Select(book => new BookLiteRow - { - Id = book.Id, - Title = book.Title, - ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear, - CoverPath = book.Artwork + IQueryable liteRowsQuery = booksQuery.Select(book => new BookLiteRow( + book.Id, + book.Title, + book.ReReleaseYear ?? book.OriginalReleaseYear, + book.Artwork .Where(artwork => artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }); + .FirstOrDefault())); // If no pagination was requested, return all the books of the library. if (paginationData is null) diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs index 4652c2d3..e7d63840 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs @@ -102,7 +102,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi DateTime nowUtc = DateTime.UtcNow; object parameters = new { libraryId, scanId, userId, nowUtc }; - // the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as lowercase hex (hex(randomblob(16))), which the storage layer parses as a Guid; + // the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as upper case hex (hex(randomblob(16))), which the storage layer parses as a Guid; // generating the Ids in code would defeat the purpose of these single statement bulk inserts // add an audit entry for every media library scan snapshot item that is no longer present in the current scan, meaning it was deleted from the storage medium diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs index 232342f7..7add1179 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/AlbumRepository.cs @@ -275,25 +275,23 @@ internal sealed class AlbumRepository : IAlbumRepository 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. + // The release year and the release types are exposed so that the clients can group and order the releases of an artist. + // The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album. 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, - // The release year and the release types are exposed so that the clients can group and order the releases of an artist. - ReleaseYear = album.ReReleaseYear ?? album.OriginalReleaseYear, - ReleaseTypes = album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList(), - // The cover of the album is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole album. - CoverPath = _luminaDbContext.MusicArtwork + .Select(album => new AlbumLiteRow( + album.Id, + album.Title, + album.TotalTracks, + _luminaDbContext.MusicArtwork .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }); + .FirstOrDefault(), + album.ReReleaseYear ?? album.OriginalReleaseYear, + album.ReleaseTypes.Select(releaseType => releaseType.ReleaseType).ToList())); if (paginationData is null) { diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs index ff9a8e08..faf9039b 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/ArtistRepository.cs @@ -565,17 +565,15 @@ internal sealed class ArtistRepository : IArtistRepository if (filterSpecification is not null) artistsQuery = artistsQuery.Where(filterSpecification.ToExpression()); + // The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist. IQueryable liteRowsQuery = ApplySorting(artistsQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker) - .Select(artist => new ArtistLiteRow - { - Id = artist.Id, - Name = artist.Name, - // The cover of the artist is the cover artwork stored for it, if any, and it is exposed so that the clients can display it without loading the whole artist. - CoverPath = _luminaDbContext.MusicArtwork + .Select(artist => new ArtistLiteRow( + artist.Id, + artist.Name, + _luminaDbContext.MusicArtwork .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }); + .FirstOrDefault())); // If no pagination was requested, return all the artists of the library. if (paginationData is null) diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index 4c440d02..7dff01b9 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -266,14 +266,12 @@ internal sealed class TrackRepository : ITrackRepository .OrderBy(track => track.DiscNumber ?? 1) // some releases don't have a disc number, assume 1 .ThenBy(track => track.TrackNumber) .ThenBy(track => track.Id) - .Select(track => new TrackLiteRow - { - Id = track.Id, - Title = track.Title, - TrackNumber = track.TrackNumber, - DiscNumber = track.DiscNumber, - DurationInSeconds = track.DurationInSeconds - }); + .Select(track => new TrackLiteRow( + track.Id, + track.Title, + track.TrackNumber, + track.DiscNumber, + track.DurationInSeconds)); if (paginationData is null) { @@ -333,24 +331,21 @@ internal sealed class TrackRepository : ITrackRepository if (excludedIds.Length > 0) query = query.Where(track => !excludedIds.Contains(track.Id)); - // SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track. + // SQLite randomizes the rows before the limit, so the result is a uniform sample of every matching track. The cover is the cover artwork stored for the album, exactly like the album cards expose it. return await query .OrderBy(_ => EF.Functions.Random()) .Take(count) - .Select(track => new ShuffleTrackRowDto - { - TrackId = track.Id, - Title = track.Title, - DurationInSeconds = track.DurationInSeconds, - AlbumId = track.AlbumId, - AlbumTitle = track.Album!.Title, - ArtistId = track.Album!.ArtistId, - // The cover is the cover artwork stored for the album, exactly like the album cards expose it. - CoverPath = _luminaDbContext.MusicArtwork + .Select(track => new ShuffleTrackRowDto( + track.Id, + track.Title, + track.DurationInSeconds, + track.AlbumId, + track.Album!.Title, + track.Album!.ArtistId, + _luminaDbContext.MusicArtwork .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == track.AlbumId && artwork.ArtworkType == ArtworkType.Cover) .Select(artwork => artwork.FileName) - .FirstOrDefault() - }) + .FirstOrDefault())) .ToListAsync(cancellationToken).ConfigureAwait(false); } @@ -529,4 +524,54 @@ internal sealed class TrackRepository : ITrackRepository .ExecuteUpdateAsync(setters => setters.SetProperty(track => track.MetadataStatus, MetadataStatus.Pending), cancellationToken).ConfigureAwait(false); return Result.Updated; } + + /// + /// Gets the number of tracks in that exist, together with the distinct Ids of the libraries that contain them. + /// + /// The Ids of the tracks whose access information is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the access summary of the existing tracks, or an error. + public async Task> GetAccessInfoByIdsAsync(IReadOnlyCollection trackIds, CancellationToken cancellationToken) + { + if (trackIds.Count == 0) + return Result.From(new TrackAccessSummaryDto(0, [])); + + // The chunk is deliberately large: it stays below the SQLite parameter limit while keeping a 100k queue to a handful of sequential round trips. + // The projection groups by library, so the storage medium returns one row per library instead of one row per requested track. + const int LOOKUP_CHUNK_SIZE = 20_000; + int trackCount = 0; + HashSet libraryIds = []; + foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + List chunkCounts = await _luminaDbContext.Tracks + .AsNoTracking() + .Where(track => chunk.Contains(track.Id)) + .GroupBy(track => track.LibraryId) + .Select(group => new TrackLibraryCount + { + LibraryId = group.Key, + TrackCount = group.Count() + }) + .ToListAsync(cancellationToken).ConfigureAwait(false); + trackCount += chunkCounts.Sum(count => count.TrackCount); + libraryIds.UnionWith(chunkCounts.Select(count => count.LibraryId)); + } + return Result.From(new TrackAccessSummaryDto(trackCount, [.. libraryIds])); + } + + /// + /// The number of requested tracks that exist in one library. + /// + private sealed class TrackLibraryCount + { + /// + /// Gets or sets the Id of the library. + /// + public Guid LibraryId { get; set; } + + /// + /// Gets or sets the number of requested tracks in the library. + /// + public int TrackCount { get; set; } + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs new file mode 100644 index 00000000..66efd106 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Playlists/PlaylistRepository.cs @@ -0,0 +1,1018 @@ +#region ========================================================================= USING ===================================================================================== +using Dapper; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.DataAccess.Common.Persistence; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.EntityFrameworkCore.Storage; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Playlists; + +/// +/// Repository for playlists. +/// +/// +/// Entry mutations are set-based because a playlist can hold a whole library. Appends bypass the change tracker, so they maintain the audit +/// columns and the denormalized entry count themselves. Positions are sparse order keys enforced by the unique (PlaylistId, Position) index. +/// +internal sealed class PlaylistRepository : IPlaylistRepository +{ + // Keeps the number of bound parameters of one multi-row INSERT well under the SQLite parameter limit. + private const int INSERT_BATCH_SIZE = 500; + // Leaves a wide numeric gap between adjacent entries, so a move or a removal normally writes one row instead of the whole range. + private const long POSITION_STEP = 1_000_000_000L; + + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public PlaylistRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a new playlist. + /// + /// The playlist 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(PlaylistEntity data, CancellationToken cancellationToken) + { + // The Id comes from the aggregate, so a row with this Id means the same playlist was already persisted, for example by a retried request. + bool doesPlaylistExist = await _luminaDbContext.Playlists + .AnyAsync(playlist => playlist.Id == data.Id, cancellationToken).ConfigureAwait(false); + if (doesPlaylistExist) + return DomainErrors.Playlists.PlaylistAlreadyExists; + + _luminaDbContext.Playlists.Add(data); + return Result.Created; + } + + /// + /// Updates the playlist identified by , applying only the editable data that actually changed, while preserving its + /// identity, its entries, and its audit columns. + /// + /// The playlist whose editable data is applied to the stored playlist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful update, or an error. + public async Task> UpdateAsync(PlaylistEntity data, CancellationToken cancellationToken) + { + // The playlist details are a scalar edit. Entry mutations are set-based repository operations, so this update never loads or reconciles the entry collection. + // A handler may already have loaded the same playlist in this unit of work, so the tracked instance is preferred over materializing a second copy. + PlaylistEntity? foundPlaylist = _luminaDbContext.Playlists.Local + .FirstOrDefault(playlist => playlist.Id == data.Id && playlist.UserId == data.UserId); + foundPlaylist ??= await _luminaDbContext.Playlists.FirstOrDefaultAsync(playlist => playlist.Id == data.Id && playlist.UserId == data.UserId, cancellationToken).ConfigureAwait(false); + if (foundPlaylist is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The stored identity is never overwritten by an edit. The audit columns stay under the ownership of the auditing interceptor, + // and the version is incremented here so a concurrent details edit or entry operation is detected. + Guid storedUserId = foundPlaylist.UserId; + long storedVersion = foundPlaylist.Version; + int storedEntryCount = foundPlaylist.EntryCount; + EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundPlaylist, data); + foundPlaylist.UserId = storedUserId; + + // The version and the entry count are not editable values of the aggregate. The count is maintained by the set-based entry + // operations, so a details edit can never overwrite it with the count of the mapped entity. + EntityEntry trackedEntry = _luminaDbContext.Entry(foundPlaylist); + trackedEntry.Property(playlist => playlist.UserId).IsModified = false; + trackedEntry.Property(playlist => playlist.Version).CurrentValue = storedVersion; + trackedEntry.Property(playlist => playlist.EntryCount).CurrentValue = storedEntryCount; + trackedEntry.Property(playlist => playlist.EntryCount).IsModified = false; + + // The version is only incremented when another editable value actually changed, so a save that leaves the details untouched does + // not stamp an activity or a concurrency change that the user never made. The comparison against the tracked original values is + // explicit, because no change detection has run between the copy and this check. + bool hasEditableChanges = trackedEntry.Properties + .Any(property => property.Metadata.Name != nameof(PlaylistEntity.Version) + && property.Metadata.Name != nameof(PlaylistEntity.EntryCount) + && !Equals(property.OriginalValue, property.CurrentValue)); + if (!hasEditableChanges) + { + trackedEntry.Property(playlist => playlist.Version).IsModified = false; + return Result.Updated; + } + foundPlaylist.Version = storedVersion + 1; + return Result.Updated; + } + + /// + /// Gets the playlist identified by when it belongs to the user identified by , if it exists. + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// Whether the entries of the playlist should be loaded together with the playlist itself. + /// Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist identified by and owned by , when no such playlist exists, or an error. + /// + public async Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default) + { + // The user is part of the filter rather than a check performed after the read, so the storage medium never returns a playlist that belongs to another user in the first place. + IQueryable query = _luminaDbContext.Playlists; + if (!shouldTrackEntities) + query = query.AsNoTracking(); + if (shouldIncludeNavigationProperties) + query = query.Include(playlist => playlist.Entries); + return await query.FirstOrDefaultAsync(playlist => playlist.Id == id && playlist.UserId == userId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the playlists of the user identified by , ordered by their most recent activity. + /// + /// The Id of the user whose playlists are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the playlists of the user, or an error. + public async Task>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken) + { + IReadOnlyList playlists = await _luminaDbContext.Playlists + .AsNoTracking() + .Where(playlist => playlist.UserId == userId) + .OrderByDescending(playlist => playlist.UpdatedOnUtc ?? playlist.CreatedOnUtc) + .ThenBy(playlist => playlist.Name) + // The count is stored on the playlist row, so listing the playlists never counts every entry of every playlist. + .Select(playlist => new PlaylistSummaryDto( + playlist.Id, + playlist.Name, + playlist.Description, + playlist.Type, + playlist.EntryCount, + playlist.CreatedOnUtc, + playlist.UpdatedOnUtc)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + return Result.From(playlists); + } + + /// + /// Gets the playlist identified by together with a window of the display details of the media items its entries reference, + /// when the playlist belongs to the user identified by . + /// + /// The Id of the playlist to get. + /// The Id of the user the playlist must belong to. + /// The zero based position of the first entry to return. + /// The maximum number of entries to return in this window. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the playlist details and its entry count, when no such playlist exists, or an error. + /// + public async Task> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken) + { + // The user is part of the filter rather than a check performed after the read, so the storage medium never returns a playlist that belongs to another user in the first place. + PlaylistEntity? playlist = await _luminaDbContext.Playlists + .AsNoTracking() + .FirstOrDefaultAsync(foundPlaylist => foundPlaylist.Id == id && foundPlaylist.UserId == userId, cancellationToken).ConfigureAwait(false); + if (playlist is null) + return Result.Success(null); + + // Only the requested window is materialized. A playlist can hold any number of entries, so the page never loads the whole list. + List windowEntries = await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == id) + .OrderBy(entry => entry.Position) + .Skip(offset) + .Take(limit) + .ToListAsync(cancellationToken).ConfigureAwait(false); + + List trackIds = [.. windowEntries + .Where(entry => entry.MediaItemType == PlaylistMediaItemType.MusicTrack) + .Select(entry => entry.MediaItemId) + .Distinct()]; + Dictionary displayDataByTrackId = await GetTrackDisplayDataAsync(trackIds, cancellationToken).ConfigureAwait(false); + + // An entry whose track was deleted is kept with no display data, so its owner can still see and remove it instead of it silently + // disappearing from the playlist. The sparse order key is converted to a dense display position for the response. + List entries = []; + for (int index = 0; index < windowEntries.Count; index++) + { + PlaylistEntryEntity entry = windowEntries[index]; + displayDataByTrackId.TryGetValue(entry.MediaItemId, out PlaylistEntryDisplayDto? displayData); + entries.Add(new PlaylistEntryDto(entry, displayData, offset + index)); + } + + return new PlaylistDetailsDto(playlist, entries); + } + + /// + /// Gets the entry that was just appended to a playlist of the user identified by , together with the display details of the media item it references. + /// + /// The Id of the playlist the entry must belong to. + /// The Id of the user the playlist must belong to. + /// The Id of the appended entry to get. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the entry details, when the entry does not exist in that playlist of the user, or an error. + /// + public async Task> GetAppendedEntryDetailsForUserAsync(Guid playlistId, Guid userId, Guid entryId, CancellationToken cancellationToken) + { + // The user is part of the join, so the read never returns an entry of a playlist that belongs to another user. + AppendedEntryState? state = await (from candidate in _luminaDbContext.PlaylistEntries.AsNoTracking() + join playlist in _luminaDbContext.Playlists on candidate.PlaylistId equals playlist.Id + where candidate.Id == entryId && candidate.PlaylistId == playlistId && playlist.UserId == userId + select new AppendedEntryState + { + Entry = candidate, + EntryCount = playlist.EntryCount + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (state is null) + return Result.Success(null); + + List trackIds = state.Entry.MediaItemType == PlaylistMediaItemType.MusicTrack ? [state.Entry.MediaItemId] : []; + Dictionary displayDataByTrackId = await GetTrackDisplayDataAsync(trackIds, cancellationToken).ConfigureAwait(false); + displayDataByTrackId.TryGetValue(state.Entry.MediaItemId, out PlaylistEntryDisplayDto? displayData); + // The appended entry is the last entry, so its dense display position is the stored entry count minus one. Counting every entry + // before it would scan an index of the whole playlist for a value that the playlist row already holds. + int displayPosition = Math.Max(0, state.EntryCount - 1); + return new PlaylistEntryDto(state.Entry, displayData, displayPosition); + } + + /// + /// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by , + /// using batched bulk inserts, and updates the activity time, the entry count and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Ids of the media items to append, in order. Duplicates are kept. + /// The kind of media item referenced by every appended entry. + /// The Ids to assign to the appended entries, in the same order as , or to generate them. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + public async Task> AddEntriesAsync(Guid playlistId, Guid userId, IReadOnlyList mediaItemIds, PlaylistMediaItemType mediaItemType, IReadOnlyList? entryIds, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + if (entryIds is not null && entryIds.Count != mediaItemIds.Count) + return DomainErrors.Playlists.PlaylistEntryIdCannotBeEmpty; + + // The shared helper owns the playlist checks, the transaction, the activity update and the entry count. The callback only writes the rows. + return await AppendEntriesAsync( + playlistId, + userId, + updatedOnUtc, + (connection, transaction, firstPosition, appendCancellationToken) => InsertEntryBatchesAsync( + connection, + transaction, + ToStorageId(playlistId), + ToStorageId(userId), + firstPosition, + mediaItemIds, + entryIds, + mediaItemType, + updatedOnUtc, + appendCancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// + /// Appends every media item of a library, an artist or an album to the end of the ordered entries of a playlist of the user identified by , in catalogue order, without materializing the scope. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The Id of the library whose media items are appended. + /// The Id of the artist the scope is limited to, or for every artist of the library. + /// The Id of the album the scope is limited to, or for every album of the scope. + /// The kind of media item referenced by every appended entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + public async Task> AddScopeEntriesAsync(Guid playlistId, Guid userId, Guid libraryId, Guid? artistId, Guid? albumId, PlaylistMediaItemType mediaItemType, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + // The callback inserts the scope with SQL instead of receiving a list, which is what keeps a whole-library append from materializing every track Id before the insert starts. + return await AppendEntriesAsync( + playlistId, + userId, + updatedOnUtc, + (connection, transaction, firstPosition, appendCancellationToken) => InsertScopeEntriesAsync( + connection, + transaction, + ToStorageId(playlistId), + ToStorageId(userId), + firstPosition, + libraryId, + artistId, + albumId, + mediaItemType, + updatedOnUtc, + appendCancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// + /// Appends entries to a playlist with a set-based operation, and updates the activity time, the entry count and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist to append to. + /// The Id of the user the playlist must belong to. + /// The activity time to store on the playlist. + /// + /// The operation that inserts the entries and returns the number of rows it inserted, using the connection, the transaction and the + /// sparse order key of the first appended entry supplied by this method. + /// + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the sparse order key of the first appended entry and the added count, or an error. + /// + private async Task> AppendEntriesAsync( + Guid playlistId, + Guid userId, + DateTime updatedOnUtc, + Func> appendEntries, + CancellationToken cancellationToken) + { + // The Ids are written in the same upper case TEXT representation the Entity Framework provider uses, so the raw inserts join the + // existing rows, their indexes and their foreign keys consistently. The registered Dapper Guid type handler uses the same form. + string playlistIdText = ToStorageId(playlistId); + string userIdText = ToStorageId(userId); + + // The raw inserts run on the connection and transaction of the request's unit of work, so they participate in the same + // atomic operation as the rest of the command instead of opening a second connection that would fight for the SQLite write lock. + DbConnection connection = _luminaDbContext.Database.GetDbConnection(); + if (connection.State != ConnectionState.Open) + await connection.OpenAsync(cancellationToken).ConfigureAwait(false); + DbTransaction? existingTransaction = _luminaDbContext.Database.CurrentTransaction?.GetDbTransaction(); + DbTransaction transaction = existingTransaction ?? await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + // The request middleware owns the transaction it opened and decides its fate. The repository only commits or rolls back a + // transaction it opened itself, which happens when it runs without an ambient request transaction. + bool ownsTransaction = existingTransaction is null; + + try + { + // The validation failures below happen before any row is written. There is therefore nothing for an ambient request transaction to roll back, so only a transaction opened here is closed. + // The append only needs to know that the playlist still exists for this user. + const string PLAYLIST_EXISTS_SQL = "SELECT 1 FROM Playlists WHERE Id = @playlistId AND UserId = @userId LIMIT 1;"; + CommandDefinition playlistExistsCommand = new(PLAYLIST_EXISTS_SQL, new { playlistId = playlistIdText, userId = userIdText }, transaction, cancellationToken: cancellationToken); + long? playlistExists = await connection.ExecuteScalarAsync(playlistExistsCommand).ConfigureAwait(false); + if (playlistExists is null) + { + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return DomainErrors.Playlists.PlaylistNotFound; + } + + // The append starts one sparse step after the highest stored key. MAX seeks the (PlaylistId, Position) index; COUNT(*) would scan the playlist for every single add. + const string FIRST_POSITION_SQL = "SELECT COALESCE(MAX(Position) + @step, 0) FROM PlaylistEntries WHERE PlaylistId = @playlistId;"; + CommandDefinition firstPositionCommand = new(FIRST_POSITION_SQL, new { playlistId = playlistIdText, step = POSITION_STEP }, transaction, cancellationToken: cancellationToken); + long firstPosition = await connection.ExecuteScalarAsync(firstPositionCommand).ConfigureAwait(false); + + int addedCount = await appendEntries(connection, transaction, firstPosition, cancellationToken).ConfigureAwait(false); + if (addedCount == 0) + { + // An empty scope is a successful no-op. The playlist activity, version and count must not change just because nothing was added. + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return new PlaylistBulkAddResultDto(firstPosition, 0); + } + + // The count is updated in the same statement, so a window read never counts the entries of a whole playlist. + const string UPDATE_ACTIVITY_SQL = """ + UPDATE Playlists + SET UpdatedOnUtc = @updatedOnUtc, UpdatedBy = @userId, Version = Version + 1, EntryCount = EntryCount + @addedCount + WHERE Id = @playlistId AND UserId = @userId; + """; + CommandDefinition updateActivityCommand = new(UPDATE_ACTIVITY_SQL, new { updatedOnUtc, playlistId = playlistIdText, userId = userIdText, addedCount }, transaction, cancellationToken: cancellationToken); + int updatedPlaylistCount = await connection.ExecuteAsync(updateActivityCommand).ConfigureAwait(false); + if (updatedPlaylistCount == 0) + { + // The entries were already written. A transaction opened here is rolled back before the error is returned; the request + // transaction is left to the middleware, which rolls it back because this command answers with a failure. + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return DomainErrors.Playlists.PlaylistNotFound; + } + + // The request middleware owns the transaction and commits it after the response, so only a transaction opened here is committed here. + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return new PlaylistBulkAddResultDto(firstPosition, addedCount); + } + catch (SqliteException exception) when (IsUniqueConstraintViolation(exception)) + { + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (SqliteException exception) when (IsConcurrencyConflict(exception)) + { + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + catch (OperationCanceledException) + { + // A client abort is reported as a non-success status by the exception handling middleware, so the request transaction is rolled + // back there. A transaction opened here still has to be closed before the exception propagates. + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + throw; + } + catch + { + // Any other failure also leaves a transaction opened here unusable, so it is closed before the failure propagates. The request + // transaction is left to the middleware, which rolls it back because the error answers with a non-success status. + await RollbackOwnedTransactionAsync(transaction, ownsTransaction).ConfigureAwait(false); + throw; + } + } + + /// + /// Inserts explicit media item Ids in bounded batches, so a long queue does not build one enormous SQL statement. + /// + /// The open connection that carries the append transaction. + /// The transaction the inserts run in. + /// The storage representation of the playlist Id. + /// The storage representation of the user Id. + /// The sparse order key of the first appended entry. + /// The Ids of the media items to append, in order. Duplicates are kept. + /// The Ids to assign to the appended entries, or to generate them. + /// The kind of media item referenced by every appended entry. + /// The activity time to stamp on the appended entries. + /// Cancellation token that can be used to stop the execution. + /// The number of inserted entries. + private static async Task InsertEntryBatchesAsync( + DbConnection connection, + DbTransaction transaction, + string playlistIdText, + string userIdText, + long firstPosition, + IReadOnlyList mediaItemIds, + IReadOnlyList? entryIds, + PlaylistMediaItemType mediaItemType, + DateTime updatedOnUtc, + CancellationToken cancellationToken) + { + for (int offset = 0; offset < mediaItemIds.Count; offset += INSERT_BATCH_SIZE) + { + cancellationToken.ThrowIfCancellationRequested(); + int count = Math.Min(INSERT_BATCH_SIZE, mediaItemIds.Count - offset); + StringBuilder insertSql = new("INSERT INTO PlaylistEntries (Id, PlaylistId, MediaItemId, MediaItemType, Position, CreatedOnUtc, CreatedBy) VALUES "); + DynamicParameters parameters = new(); + parameters.Add("mediaItemType", mediaItemType.ToString()); + parameters.Add("createdOnUtc", updatedOnUtc); + parameters.Add("createdBy", userIdText); + for (int index = 0; index < count; index++) + { + if (index > 0) + insertSql.Append(", "); + insertSql.Append($"(@Id{index}, @PlaylistId{index}, @MediaItemId{index}, @mediaItemType, @Position{index}, @createdOnUtc, @createdBy)"); + Guid entryId = entryIds is null ? Guid.NewGuid() : entryIds[offset + index]; + parameters.Add($"Id{index}", ToStorageId(entryId)); + parameters.Add($"PlaylistId{index}", playlistIdText); + parameters.Add($"MediaItemId{index}", ToStorageId(mediaItemIds[offset + index])); + // Every appended entry is one sparse step after the previous one, so later moves can change a single key without rewriting the entries that follow it. + parameters.Add($"Position{index}", firstPosition + ((offset + index) * POSITION_STEP)); + } + CommandDefinition insertCommand = new(insertSql.ToString(), parameters, transaction, cancellationToken: cancellationToken); + await connection.ExecuteAsync(insertCommand).ConfigureAwait(false); + } + // The caller uses this count to update the stored entry count, so it returns the requested rows rather than the number of batches. + return mediaItemIds.Count; + } + + /// + /// Inserts every track of a library, an artist or an album with one INSERT ... SELECT statement, in catalogue order, so the scope is + /// never materialized and sorted in memory. + /// + /// The open connection that carries the append transaction. + /// The transaction the insert runs in. + /// The storage representation of the playlist Id. + /// The storage representation of the user Id. + /// The sparse order key of the first appended entry. + /// The Id of the library whose tracks are appended. + /// The Id of the artist the scope is limited to, or for every artist of the library. + /// The Id of the album the scope is limited to, or for every album of the scope. + /// The kind of media item referenced by every appended entry. + /// The activity time to stamp on the appended entries. + /// Cancellation token that can be used to stop the execution. + /// The number of inserted entries. + private static async Task InsertScopeEntriesAsync( + DbConnection connection, + DbTransaction transaction, + string playlistIdText, + string userIdText, + long firstPosition, + Guid libraryId, + Guid? artistId, + Guid? albumId, + PlaylistMediaItemType mediaItemType, + DateTime updatedOnUtc, + CancellationToken cancellationToken) + { + // The entry Ids are generated by SQLite in the same upper case, hyphenated TEXT form the Entity Framework provider stores. Generating + // them inside the statement is what lets the scope stay a single insert instead of being materialized in C# just to assign Ids. + // The positions are computed by the same ordering the artist and album pages use, so the playlist receives catalogue order directly. + // ROW_NUMBER() produces the dense rank, and multiplying it by POSITION_STEP keeps the stored keys sparse. + StringBuilder insertSql = new(""" + INSERT INTO PlaylistEntries (Id, PlaylistId, MediaItemId, MediaItemType, Position, CreatedOnUtc, CreatedBy) + SELECT + HEX(RANDOMBLOB(4)) || '-' || HEX(RANDOMBLOB(2)) || '-' || HEX(RANDOMBLOB(2)) || '-' || HEX(RANDOMBLOB(2)) || '-' || HEX(RANDOMBLOB(6)), + @playlistId, + track.Id, + @mediaItemType, + @firstPosition + (ROW_NUMBER() OVER (ORDER BY artist.Name, album.Title, album.OriginalReleaseYear, COALESCE(track.DiscNumber, 1), track.TrackNumber, track.Id) - 1) * @step, + @createdOnUtc, + @createdBy + FROM Tracks AS track + INNER JOIN Albums AS album ON album.Id = track.AlbumId + INNER JOIN Artists AS artist ON artist.Id = album.ArtistId + WHERE track.LibraryId = @libraryId + """); + if (artistId is not null) + insertSql.Append(" AND album.ArtistId = @artistId"); + if (albumId is not null) + insertSql.Append(" AND track.AlbumId = @albumId"); + insertSql.Append(';'); + + DynamicParameters parameters = new(); + parameters.Add("playlistId", playlistIdText); + parameters.Add("libraryId", ToStorageId(libraryId)); + parameters.Add("mediaItemType", mediaItemType.ToString()); + parameters.Add("firstPosition", firstPosition); + parameters.Add("step", POSITION_STEP); + parameters.Add("createdOnUtc", updatedOnUtc); + parameters.Add("createdBy", userIdText); + if (artistId is not null) + parameters.Add("artistId", ToStorageId(artistId.Value)); + if (albumId is not null) + parameters.Add("albumId", ToStorageId(albumId.Value)); + + CommandDefinition insertCommand = new(insertSql.ToString(), parameters, transaction, cancellationToken: cancellationToken); + return await connection.ExecuteAsync(insertCommand).ConfigureAwait(false); + } + + /// + /// Moves one entry of a playlist of the user identified by to a new dense position by changing only its + /// sparse order key, and updates the activity time and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is moved. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to move. + /// The new zero based position of the entry. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful move, or an error. + public async Task> MoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, int targetPosition, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + try + { + // The version, the entry count and the existence of the entry are read in one statement. The count comes from the playlist + // row, so a drag on a very large playlist never scans the entry index to find out how many entries it holds. Keeping the + // existence check in the same query also preserves the not-found result for a one-entry playlist, where no entry update runs. + PlaylistMoveState? playlistState = await _luminaDbContext.Playlists + .AsNoTracking() + .Where(playlist => playlist.Id == playlistId && playlist.UserId == userId) + .Select(playlist => new PlaylistMoveState + { + Version = playlist.Version, + EntryCount = playlist.EntryCount, + DoesEntryExist = _luminaDbContext.PlaylistEntries.Any(entry => entry.Id == entryId && entry.PlaylistId == playlistId) + }) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (playlistState is null) + return DomainErrors.Playlists.PlaylistNotFound; + if (!playlistState.DoesEntryExist) + return DomainErrors.Playlists.PlaylistEntryNotFound; + + long playlistVersion = playlistState.Version; + int entryCount = playlistState.EntryCount; + if (targetPosition < 0 || targetPosition >= entryCount) + return DomainErrors.Playlists.PlaylistMoveTargetPositionIsInvalid; + + // A one-entry playlist has no order to change, so only the activity time is updated below. + if (entryCount > 1) + { + long newPosition; + if (targetPosition == 0) + { + // Moving to the front needs a sparse key before the current first entry. + long? nextPosition = await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId && entry.Id != entryId) + .OrderBy(entry => entry.Position) + .Select(entry => (long?)entry.Position) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (nextPosition is null) + return ApplicationErrors.Persistence.ConcurrencyConflict; + newPosition = nextPosition.Value - POSITION_STEP; + } + else if (targetPosition == entryCount - 1) + { + // Moving to the end needs a sparse key after the current last entry. + long? previousPosition = await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId && entry.Id != entryId) + .OrderByDescending(entry => entry.Position) + .Select(entry => (long?)entry.Position) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (previousPosition is null) + return ApplicationErrors.Persistence.ConcurrencyConflict; + newPosition = previousPosition.Value + POSITION_STEP; + } + else + { + // A middle move only needs the two rows that will surround the moved entry. Its new key is the midpoint between them. + List neighbors = await GetMoveNeighborsAsync(playlistId, entryId, targetPosition, cancellationToken).ConfigureAwait(false); + if (neighbors.Count < 2) + return ApplicationErrors.Persistence.ConcurrencyConflict; + if (neighbors[1] - neighbors[0] <= 1) + { + // The numeric gap between the two neighbors was exhausted by earlier midpoint moves. This is the rare repair path; + // it rewrites the order keys once, then the move continues with a fresh gap. + await RebalancePositionsAsync(playlistId, cancellationToken).ConfigureAwait(false); + neighbors = await GetMoveNeighborsAsync(playlistId, entryId, targetPosition, cancellationToken).ConfigureAwait(false); + if (neighbors.Count < 2) + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + long gap = neighbors[1] - neighbors[0]; + if (gap <= 1) + return ApplicationErrors.Persistence.ConcurrencyConflict; + newPosition = neighbors[0] + (gap / 2); + } + + int updatedEntryCount = await _luminaDbContext.PlaylistEntries + .Where(entry => entry.Id == entryId && entry.PlaylistId == playlistId) + .ExecuteUpdateAsync(setters => setters + .SetProperty(entry => entry.Position, newPosition) + .SetProperty(entry => entry.UpdatedOnUtc, updatedOnUtc) + .SetProperty(entry => entry.UpdatedBy, (Guid?)userId), cancellationToken).ConfigureAwait(false); + if (updatedEntryCount == 0) + return DomainErrors.Playlists.PlaylistEntryNotFound; + } + + int updatedPlaylistCount = await UpdatePlaylistActivityAsync(playlistId, userId, playlistVersion, updatedOnUtc, entryCountDelta: 0, cancellationToken).ConfigureAwait(false); + if (updatedPlaylistCount == 0) + return ApplicationErrors.Persistence.ConcurrencyConflict; + return Result.Updated; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsUniqueConstraintViolation(sqliteException)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsConcurrencyConflict(sqliteException)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + catch (SqliteException exception) when (IsUniqueConstraintViolation(exception)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (SqliteException exception) when (IsConcurrencyConflict(exception)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + } + + /// + /// Removes one entry of a playlist of the user identified by by deleting only that row, and updates the + /// activity time, the entry count and the concurrency token of the playlist in the same transaction. + /// + /// The Id of the playlist whose entry is removed. + /// The Id of the user the playlist must belong to. + /// The Id of the entry to remove. + /// The activity time to store on the playlist. + /// Cancellation token that can be used to stop the execution. + /// An containing either zero repositioned entries, or an error. + public async Task> RemoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, DateTime updatedOnUtc, CancellationToken cancellationToken) + { + try + { + // The version is captured before the delete, so the following count update only applies if no other writer changed the playlist meanwhile. + long? playlistVersion = await _luminaDbContext.Playlists + .AsNoTracking() + .Where(playlist => playlist.Id == playlistId && playlist.UserId == userId) + .Select(playlist => (long?)playlist.Version) + .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + if (playlistVersion is null) + return DomainErrors.Playlists.PlaylistNotFound; + + // The delete reports how many rows it removed, so a missing or already removed entry needs no separate existence query. + int deletedEntryCount = await _luminaDbContext.PlaylistEntries + .Where(entry => entry.Id == entryId && entry.PlaylistId == playlistId) + .ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false); + if (deletedEntryCount == 0) + return DomainErrors.Playlists.PlaylistEntryNotFound; + + // The deleted row decrements the stored count by one. The version predicate ties that decrement to the version read above, so a + // concurrent writer is reported instead of leaving the count out of step with the entries. + int updatedPlaylistCount = await UpdatePlaylistActivityAsync(playlistId, userId, playlistVersion.Value, updatedOnUtc, entryCountDelta: -1, cancellationToken).ConfigureAwait(false); + if (updatedPlaylistCount == 0) + return ApplicationErrors.Persistence.ConcurrencyConflict; + return 0; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsUniqueConstraintViolation(sqliteException)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (DbUpdateException exception) when (exception.InnerException is SqliteException sqliteException && IsConcurrencyConflict(sqliteException)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + catch (SqliteException exception) when (IsUniqueConstraintViolation(exception)) + { + return ApplicationErrors.Persistence.UniqueConstraintViolation; + } + catch (SqliteException exception) when (IsConcurrencyConflict(exception)) + { + return ApplicationErrors.Persistence.ConcurrencyConflict; + } + } + + /// + /// Gets the two entries that surround the dense target position, excluding the entry being moved. + /// + /// The Id of the playlist. + /// The Id of the entry being moved. + /// The dense target position of the moved entry. + /// Cancellation token that can be used to stop the execution. + /// The sparse order keys of the previous and next entries at the target position. + private async Task> GetMoveNeighborsAsync(Guid playlistId, Guid entryId, int targetPosition, CancellationToken cancellationToken) + { + // The moved entry is excluded from the ordering, so the dense target position maps to the two rows before and after it. + return await _luminaDbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId && entry.Id != entryId) + .OrderBy(entry => entry.Position) + .Skip(targetPosition - 1) + .Take(2) + .Select(entry => entry.Position) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Rewrites the sparse order keys of a playlist to evenly spaced values. + /// + /// + /// This is a rare repair path, used only when repeated midpoint moves exhaust the numeric gap between two adjacent entries. It runs on + /// the request connection and transaction, parks every row at a unique negative key, and then applies the new keys from a temporary table + /// so the unique index is never violated during the rewrite. + /// + /// The Id of the playlist whose order keys are rewritten. + /// Cancellation token that can be used to stop the execution. + /// A task representing the asynchronous operation. + private async Task RebalancePositionsAsync(Guid playlistId, CancellationToken cancellationToken) + { + string playlistIdText = ToStorageId(playlistId); + DbConnection connection = _luminaDbContext.Database.GetDbConnection(); + if (connection.State != ConnectionState.Open) + await connection.OpenAsync(cancellationToken).ConfigureAwait(false); + DbTransaction? existingTransaction = _luminaDbContext.Database.CurrentTransaction?.GetDbTransaction(); + DbTransaction transaction = existingTransaction ?? await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false); + bool ownsTransaction = existingTransaction is null; + try + { + const string MIN_POSITION_SQL = "SELECT MIN(Position) FROM PlaylistEntries WHERE PlaylistId = @playlistId;"; + CommandDefinition minPositionCommand = new(MIN_POSITION_SQL, new { playlistId = playlistIdText }, transaction, cancellationToken: cancellationToken); + long? minPosition = await connection.ExecuteScalarAsync(minPositionCommand).ConfigureAwait(false); + if (minPosition is null) + { + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return; + } + + const string DROP_TEMP_TABLE_SQL = "DROP TABLE IF EXISTS PlaylistPositionRebalance;"; + const string CREATE_TEMP_TABLE_SQL = "CREATE TEMP TABLE PlaylistPositionRebalance (Id TEXT NOT NULL PRIMARY KEY, Position INTEGER NOT NULL, ParkPosition INTEGER NOT NULL);"; + // The final keys and a temporary unique negative key are computed once, in playlist order. + const string FILL_TEMP_TABLE_SQL = """ + INSERT INTO PlaylistPositionRebalance (Id, Position, ParkPosition) + SELECT Id, + (ROW_NUMBER() OVER (ORDER BY Position) - 1) * @step, + @minPosition - ROW_NUMBER() OVER (ORDER BY Position) + FROM PlaylistEntries + WHERE PlaylistId = @playlistId; + """; + // Every row is first moved to its unique negative key, so applying the final keys cannot collide with the unique index. + const string PARK_SQL = """ + UPDATE PlaylistEntries + SET Position = ( + SELECT ParkPosition + FROM PlaylistPositionRebalance + WHERE PlaylistPositionRebalance.Id = PlaylistEntries.Id + ) + WHERE PlaylistId = @playlistId; + """; + // The negative keys are then replaced by the final evenly spaced keys. + const string APPLY_SQL = """ + UPDATE PlaylistEntries + SET Position = ( + SELECT Position + FROM PlaylistPositionRebalance + WHERE PlaylistPositionRebalance.Id = PlaylistEntries.Id + ) + WHERE PlaylistId = @playlistId; + """; + object parameters = new { playlistId = playlistIdText, step = POSITION_STEP, minPosition = minPosition.Value }; + List commands = + [ + new(DROP_TEMP_TABLE_SQL, transaction: transaction, cancellationToken: cancellationToken), + new(CREATE_TEMP_TABLE_SQL, transaction: transaction, cancellationToken: cancellationToken), + new(FILL_TEMP_TABLE_SQL, parameters, transaction, cancellationToken: cancellationToken), + new(PARK_SQL, parameters, transaction, cancellationToken: cancellationToken), + new(APPLY_SQL, parameters, transaction, cancellationToken: cancellationToken), + new(DROP_TEMP_TABLE_SQL, transaction: transaction, cancellationToken: cancellationToken) + ]; + foreach (CommandDefinition command in commands) + await connection.ExecuteAsync(command).ConfigureAwait(false); + if (ownsTransaction) + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + } + catch + { + if (ownsTransaction) + await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false); + throw; + } + } + + /// + /// Deletes the playlist identified by . + /// + /// The Id of the playlist 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) + { + PlaylistEntity? playlist = await _luminaDbContext.Playlists + .FirstOrDefaultAsync(foundPlaylist => foundPlaylist.Id == id, cancellationToken).ConfigureAwait(false); + if (playlist is null) + return DomainErrors.Playlists.PlaylistNotFound; + + _luminaDbContext.Playlists.Remove(playlist); + return Result.Deleted; + } + + /// + /// Updates the activity time, the entry count and the concurrency token of the playlist identified by , when its version still matches . + /// + /// The Id of the playlist to update. + /// The Id of the user the playlist must belong to. + /// The concurrency token the playlist must still carry. + /// The activity time to store on the playlist. + /// The number of entries the operation added to or removed from the playlist. + /// Cancellation token that can be used to stop the execution. + /// The number of playlist rows that were updated. + private async Task UpdatePlaylistActivityAsync(Guid playlistId, Guid userId, long expectedVersion, DateTime updatedOnUtc, int entryCountDelta, CancellationToken cancellationToken) + { + // ExecuteUpdate sends one UPDATE and never loads the entries or the playlist. The version predicate is the optimistic concurrency + // check, and the returned row count tells the caller whether another writer won the race. + return await _luminaDbContext.Playlists + .Where(playlist => playlist.Id == playlistId && playlist.UserId == userId && playlist.Version == expectedVersion) + .ExecuteUpdateAsync(setters => setters + .SetProperty(playlist => playlist.UpdatedOnUtc, updatedOnUtc) + .SetProperty(playlist => playlist.UpdatedBy, (Guid?)userId) + .SetProperty(playlist => playlist.EntryCount, playlist => playlist.EntryCount + entryCountDelta) + .SetProperty(playlist => playlist.Version, playlist => playlist.Version + 1), cancellationToken).ConfigureAwait(false); + } + + /// + /// Rolls back a transaction that this repository opened, leaving the request's ambient transaction untouched when it did not open one. + /// + /// + /// The request middleware owns the transaction it opened, and it commits or rolls it back once the response status is known. The repository + /// only closes a transaction it opened itself, so it never takes a decision about work that belongs to the request. + /// + /// The transaction to roll back. + /// Whether this repository opened the transaction. + /// A task representing the asynchronous operation. + private static async Task RollbackOwnedTransactionAsync(DbTransaction transaction, bool ownsTransaction) + { + if (!ownsTransaction) + return; + // Cleanup still has to run when the request token has already been cancelled, which is exactly the failure path that reaches here. + await transaction.RollbackAsync(CancellationToken.None).ConfigureAwait(false); + } + + /// + /// Reads the display details of the tracks identified by with their album, artist and cover, in a single + /// query per bounded chunk. + /// + /// The Ids of the tracks whose display details are read. + /// Cancellation token that can be used to stop the execution. + /// The display details keyed by track Id. + private async Task> GetTrackDisplayDataAsync(IReadOnlyCollection trackIds, CancellationToken cancellationToken) + { + if (trackIds.Count == 0) + return []; + + // The album and the artist are joined by Id, so a playlist never issues a query per entry. The cover is the one stored for the album + // of the track. The lookup is split into bounded chunks, so even a large requested window never exceeds the storage parameter limit. + const int LOOKUP_CHUNK_SIZE = 500; + List trackDetails = []; + foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE)) + { + List chunkDetails = await (from track in _luminaDbContext.Tracks.AsNoTracking() + join album in _luminaDbContext.Albums on track.AlbumId equals album.Id + join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id + where chunk.Contains(track.Id) + select new PlaylistEntryDisplayDto( + track.Id, + track.Title, + track.DurationInSeconds, + track.LibraryId, + track.AlbumId, + album.Title, + artist.Id, + artist.Name, + _luminaDbContext.MusicArtwork + .Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album + && artwork.OwnerId == album.Id + && artwork.ArtworkType == ArtworkType.Cover) + .Select(artwork => artwork.FileName) + .FirstOrDefault())) + .ToListAsync(cancellationToken).ConfigureAwait(false); + trackDetails.AddRange(chunkDetails); + } + return trackDetails.ToDictionary(track => track.TrackId); + } + + /// + /// Determines whether reports a unique constraint violation. + /// + /// The storage exception to inspect. + /// for a unique constraint violation, otherwise. + private static bool IsUniqueConstraintViolation(SqliteException exception) + { + return exception.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE + } + + /// + /// Determines whether reports a busy or locked SQLite database. + /// + /// The storage exception to inspect. + /// for a busy or locked database, otherwise. + private static bool IsConcurrencyConflict(SqliteException exception) + { + return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED + } + + /// + /// Converts an Id to the TEXT representation used by the Entity Framework SQLite provider for columns. + /// + /// + /// Entity Framework and the Dapper parameter binding both write values as upper case TEXT. + /// + /// The Id to convert. + /// The upper case TEXT representation of the Id. + private static string ToStorageId(Guid value) + { + return value.ToString().ToUpperInvariant(); + } + + /// + /// The concurrency token and entry count of a playlist, together with whether a specific entry exists in it. + /// + private sealed class PlaylistMoveState + { + /// + /// Gets or sets the concurrency token of the playlist. + /// + public long Version { get; init; } + + /// + /// Gets or sets the number of entries the playlist holds. + /// + public int EntryCount { get; init; } + + /// + /// Gets or sets whether the moved entry exists in the playlist. + /// + public bool DoesEntryExist { get; init; } + } + + /// + /// The appended entry and the stored entry count of its playlist. + /// + private sealed class AppendedEntryState + { + /// + /// Gets or sets the appended entry. + /// + public PlaylistEntryEntity Entry { get; init; } = null!; + + /// + /// Gets or sets the number of entries the playlist holds after the append. + /// + public int EntryCount { get; init; } + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index 08f88a19..2d383e42 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaContributors; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.Scheduling; using Lumina.Application.Common.DataAccess.Entities.Themes; @@ -50,6 +51,8 @@ public class LuminaDbContext : DbContext public virtual DbSet ScheduledJobExecutions { get; set; } = null!; public virtual DbSet SchedulerDisplayPreferences { get; set; } = null!; public virtual DbSet MusicPlayRecords { get; set; } = null!; + public virtual DbSet Playlists { get; set; } = null!; + public virtual DbSet PlaylistEntries { get; set; } = null!; /// /// Initializes a new instance of the class. diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index a669e642..a0eca8bd 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.MediaContributors; using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Scheduling; using Lumina.Application.Common.DataAccess.Repositories.Themes; @@ -15,6 +16,7 @@ using Lumina.DataAccess.Core.Repositories.BookLibrary; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.Repositories.MediaContributors; using Lumina.DataAccess.Core.Repositories.MusicLibrary; +using Lumina.DataAccess.Core.Repositories.Playlists; using Lumina.DataAccess.Core.Repositories.Plugins; using Lumina.DataAccess.Core.Repositories.Scheduling; using Lumina.DataAccess.Core.Repositories.Themes; @@ -65,6 +67,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable private IUserRepository? _userRepository; private IUserSettingsRepository? _userSettingsRepository; private IMusicPlayRecordRepository? _musicPlayRecordRepository; + private IPlaylistRepository? _playlistRepository; /// /// Gets the permission repository. @@ -387,6 +390,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the playlist repository. + /// + public IPlaylistRepository PlaylistRepository + { + get + { + _playlistRepository ??= new PlaylistRepository(_luminaDbContext); + return _playlistRepository; + } + } + /// /// Initializes a new instance of the class. /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs new file mode 100644 index 00000000..37e81b01 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistMediaItemType.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media item an ordered playlist entry can reference. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistMediaItemType +{ + /// + /// An entry that references a music track. + /// + MusicTrack, + + /// + /// An entry that references a video file. + /// + VideoFile, +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs new file mode 100644 index 00000000..369e7554 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playlists/PlaylistType.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media a playlist can hold. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistType +{ + /// + /// A playlist whose ordered entries reference music tracks. + /// + Music, +} diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playlist.cs b/src/Lumina.Domain/Common/Errors/Errors.Playlist.cs new file mode 100644 index 00000000..0def7b24 --- /dev/null +++ b/src/Lumina.Domain/Common/Errors/Errors.Playlist.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +#endregion + +namespace Lumina.Domain.Common.Errors; + +/// +/// Playlist error types. +/// +public static partial class Errors +{ + public static class Playlists + { + public static Error PlaylistNotFound => Error.NotFound(description: nameof(PlaylistNotFound)); + public static Error PlaylistAlreadyExists => Error.Conflict(description: nameof(PlaylistAlreadyExists)); + public static Error PlaylistIdCannotBeEmpty => Error.Validation(description: nameof(PlaylistIdCannotBeEmpty)); + public static Error PlaylistEntryIdCannotBeEmpty => Error.Validation(description: nameof(PlaylistEntryIdCannotBeEmpty)); + public static Error PlaylistNameCannotBeEmpty => Error.Validation(description: nameof(PlaylistNameCannotBeEmpty)); + public static Error PlaylistNameMustBeMaximum255CharactersLong => Error.Validation(description: nameof(PlaylistNameMustBeMaximum255CharactersLong)); + public static Error PlaylistDescriptionMustBeMaximum2000CharactersLong => Error.Validation(description: nameof(PlaylistDescriptionMustBeMaximum2000CharactersLong)); + public static Error PlaylistTypeIsInvalid => Error.Validation(description: nameof(PlaylistTypeIsInvalid)); + public static Error PlaylistDoesNotAcceptMediaItems => Error.Forbidden(description: nameof(PlaylistDoesNotAcceptMediaItems)); + public static Error PlaylistEntryNotFound => Error.NotFound(description: nameof(PlaylistEntryNotFound)); + public static Error PlaylistEntryPositionsAreInvalid => Error.Validation(description: nameof(PlaylistEntryPositionsAreInvalid)); + public static Error PlaylistMoveTargetPositionIsInvalid => Error.Validation(description: nameof(PlaylistMoveTargetPositionIsInvalid)); + public static Error PlaylistEntryWindowOffsetIsInvalid => Error.Validation(description: nameof(PlaylistEntryWindowOffsetIsInvalid)); + public static Error PlaylistEntryWindowLimitIsInvalid => Error.Validation(description: nameof(PlaylistEntryWindowLimitIsInvalid)); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs new file mode 100644 index 00000000..37adf434 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemId.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; + +/// +/// Value Object for the Id of a media item, duplicated from the media library bounded contexts to keep the cross bounded context references decoupled. +/// +/// +/// The kind of media item is carried by the playlist entry and by the playlist type, so this identifier stays generic across music tracks and video files. +/// +[DebuggerDisplay("{Value}")] +public sealed class MediaItemId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private MediaItemId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static MediaItemId CreateUnique() + { + return new MediaItemId(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 MediaItemId Create(Guid value) + { + return new MediaItemId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs new file mode 100644 index 00000000..1104b077 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// +[DebuggerDisplay("{Value}")] +public sealed class UserId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private UserId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static UserId CreateUnique() + { + return new UserId(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 UserId Create(Guid value) + { + return new UserId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs new file mode 100644 index 00000000..50b9aa0c --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntry.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; + +/// +/// Entity for an ordered entry of a playlist. +/// +[DebuggerDisplay("Id: {Id.Value}; MediaItemId: {MediaItemId.Value}; MediaItemType: {MediaItemType}; Position: {Position}")] +public sealed class PlaylistEntry : Entity +{ + /// + /// Gets the Id of the media item referenced by the entry. + /// + public MediaItemId MediaItemId { get; private set; } + + /// + /// Gets the kind of media item referenced by the entry. + /// + public PlaylistMediaItemType MediaItemType { get; private set; } + + /// + /// Gets the sparse order key of the entry in the ordered entries of the playlist. + /// + public long Position { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the entry. + /// The Id of the media item referenced by the entry. + /// The kind of media item referenced by the entry. + /// The sparse order key of the entry in the ordered entries of the playlist. + private PlaylistEntry(PlaylistEntryId id, MediaItemId mediaItemId, PlaylistMediaItemType mediaItemType, long position) : base(id) + { + Id = id; + MediaItemId = mediaItemId; + MediaItemType = mediaItemType; + Position = position; + } + + /// + /// Creates a new instance of the class, with a pre-existing . + /// + /// The object representing the unique identifier of the entry. + /// The Id of the media item referenced by the entry. + /// The kind of media item referenced by the entry. + /// The sparse order key of the entry in the ordered entries of the playlist. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(PlaylistEntryId id, MediaItemId mediaItemId, PlaylistMediaItemType mediaItemType, long position) + { + return new PlaylistEntry(id, mediaItemId, mediaItemType, position); + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs new file mode 100644 index 00000000..992b4be9 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEvent.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Domain event raised when a playlist is created. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the playlist. +/// The unique identifier of the user that owns the playlist. +/// The name of the playlist. +/// The kind of media the playlist holds. +/// The date and time when the domain event occurred. +[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; UserId: {UserId.Value}")] +public record PlaylistCreatedDomainEvent( + Guid Id, + PlaylistId PlaylistId, + UserId UserId, + string Name, + PlaylistType Type, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs new file mode 100644 index 00000000..8fbf84b9 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEvent.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Domain event raised when a playlist is deleted. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the playlist. +/// The unique identifier of the user that owned the playlist. +/// The date and time when the domain event occurred. +[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; UserId: {UserId.Value}")] +public record PlaylistDeletedDomainEvent( + Guid Id, + PlaylistId PlaylistId, + UserId UserId, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs new file mode 100644 index 00000000..03cf3861 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEvent.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Domain event raised when the details of a playlist are updated. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the playlist. +/// The unique identifier of the user that owns the playlist. +/// The new name of the playlist. +/// The date and time when the domain event occurred. +[DebuggerDisplay("PlaylistId: {PlaylistId.Value}; Name: {Name}")] +public record PlaylistDetailsUpdatedDomainEvent( + Guid Id, + PlaylistId PlaylistId, + UserId UserId, + string Name, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs new file mode 100644 index 00000000..b18e7986 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Playlist.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Models.Core; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; + +/// +/// Aggregate root for a playlist. +/// +[DebuggerDisplay("Id: {Id.Value}; Name: {Name}; Type: {Type}")] +public sealed class Playlist : AggregateRoot +{ + private readonly List _entries; + + /// + /// Gets the object representing the unique identifier of the user that owns the playlist. + /// + public UserId UserId { get; private set; } + + /// + /// Gets the name of the playlist. + /// + public string Name { get; private set; } + + /// + /// Gets the description of the playlist, if applicable. + /// + public Optional Description { get; private set; } + + /// + /// Gets the kind of media the playlist holds. + /// + public PlaylistType Type { get; private set; } + + /// + /// Gets a value indicating whether the playlist was marked for deletion in this unit of work. + /// + public bool IsDeleted { get; private set; } + + /// + /// Gets the ordered entries of the playlist. + /// + public IReadOnlyCollection Entries => _entries.AsReadOnly(); + + /// + /// Initializes a new instance of the class. + /// + /// The object representing the unique identifier of the playlist. + /// The object representing the unique identifier of the user that owns the playlist. + /// The name of the playlist. + /// The optional description of the playlist. + /// The kind of media the playlist holds. + /// The ordered entries of the playlist. + /// The date and time when the playlist was created. + /// The date and time when the playlist was last updated. + private Playlist( + PlaylistId id, + UserId userId, + string name, + Optional description, + PlaylistType type, + List entries, + DateTime createdOnUtc, + Optional updatedOnUtc) : base(id) + { + Id = id; + UserId = userId; + Name = name; + Description = description; + Type = type; + _entries = entries; + CreatedOnUtc = createdOnUtc; + UpdatedOnUtc = updatedOnUtc; + } + + /// + /// Creates a new playlist for the user identified by . + /// + /// The object representing the unique identifier of the user that owns the playlist. + /// The name of the playlist. + /// The optional description of the playlist. + /// The kind of media the playlist holds. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create(UserId userId, string name, Optional description, PlaylistType type) + { + DateTime occurredOnUtc = DateTime.UtcNow; + Playlist playlist = new( + PlaylistId.CreateUnique(), + userId, + name, + description, + type, + [], + occurredOnUtc, + Optional.None()); + + playlist._domainEvents.Add(new PlaylistCreatedDomainEvent( + Guid.NewGuid(), + playlist.Id, + userId, + name, + type, + occurredOnUtc)); + return playlist; + } + + /// + /// Creates a new instance of the class, with pre-existing data. + /// + /// The object representing the unique identifier of the playlist. + /// The object representing the unique identifier of the user that owns the playlist. + /// The name of the playlist. + /// The optional description of the playlist. + /// The kind of media the playlist holds. + /// The ordered entries of the playlist. + /// The date and time when the playlist was created. + /// The date and time when the playlist was last updated. + /// + /// An containing either a successfully created , or an error message. + /// + public static Result Create( + PlaylistId id, + UserId userId, + string name, + Optional description, + PlaylistType type, + List entries, + DateTime createdOnUtc, + Optional updatedOnUtc) + { + if (entries.Any(entry => !CanContain(type, entry.MediaItemType))) + return Errors.Playlists.PlaylistDoesNotAcceptMediaItems; + // The positions are sparse order keys, so they must be unique. The gaps between them are intentional and are not a reason to reject an otherwise readable playlist. + if (!ArePositionsValid(entries)) + return Errors.Playlists.PlaylistEntryPositionsAreInvalid; + + return new Playlist(id, userId, name, description, type, entries, createdOnUtc, updatedOnUtc); + } + + /// + /// Updates the name and the description of the playlist, without touching its entries. + /// + /// The name of the playlist. + /// The optional description of the playlist. + /// An representing either a successful update, or an error. + public Result UpdateDetails(string name, Optional description) + { + bool hasChanged = Name != name + || Description.HasValue != description.HasValue + || (Description.HasValue && description.HasValue && Description.Value != description.Value); + if (!hasChanged) + return Result.Updated; + + Name = name; + Description = description; + DateTime occurredOnUtc = DateTime.UtcNow; + _domainEvents.Add(new PlaylistDetailsUpdatedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + name, + occurredOnUtc)); + return Result.Updated; + } + + /// + /// Marks the playlist as deleted, raising the domain event that announces its deletion. + /// + /// An representing either a successful operation, or an error. + public Result Delete() + { + if (IsDeleted) + return Result.Deleted; + + // Earlier events become irrelevant once the playlist is deleted. + _domainEvents.Clear(); + IsDeleted = true; + _domainEvents.Add(new PlaylistDeletedDomainEvent( + Guid.NewGuid(), + Id, + UserId, + DateTime.UtcNow)); + return Result.Deleted; + } + + /// + /// Determines whether a playlist of can contain . + /// + /// The kind of media the playlist holds. + /// The kind of media item referenced by an entry. + /// if the media item type belongs to the playlist type, otherwise. + public static bool CanContain(PlaylistType playlistType, PlaylistMediaItemType mediaItemType) + { + return playlistType switch + { + PlaylistType.Music => mediaItemType == PlaylistMediaItemType.MusicTrack, + _ => false + }; + } + + /// + /// Determines whether the positions of are unique. + /// + /// The entries whose positions are checked. + /// if the positions are unique, otherwise. + private static bool ArePositionsValid(IReadOnlyCollection entries) + { + // The storage enforces unique order keys with a unique index, and the sparse keys are allowed to have wide gaps. + HashSet positions = []; + foreach (PlaylistEntry entry in entries) + if (!positions.Add(entry.Position)) + return false; + return true; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs new file mode 100644 index 00000000..18378ef6 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Value Object for the Id of an entry of a playlist. +/// +[DebuggerDisplay("{Value}")] +public sealed class PlaylistEntryId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private PlaylistEntryId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static PlaylistEntryId CreateUnique() + { + return new PlaylistEntryId(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 PlaylistEntryId Create(Guid value) + { + return new PlaylistEntryId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs new file mode 100644 index 00000000..786941bb --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistId.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Value Object for the Id of a playlist. +/// +[DebuggerDisplay("{Value}")] +public sealed class PlaylistId : EntityId +{ + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + private PlaylistId(Guid value) : base(value) + { + } + + /// + /// Creates a new instance of the class. + /// + /// The created instance. + public static PlaylistId CreateUnique() + { + return new PlaylistId(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 PlaylistId Create(Guid value) + { + return new PlaylistId(value); + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs index 8af9c718..271b3e7e 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/SchedulingBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserId.cs @@ -8,7 +8,7 @@ using System.Diagnostics; namespace Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; /// -/// Value object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. +/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled. /// [DebuggerDisplay("{Value}")] public sealed class UserId : EntityId diff --git a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs index c3269050..72c402be 100644 --- a/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs +++ b/src/Lumina.Infrastructure/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicy.cs @@ -1,11 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Domain.Common.Primitives; using System; +using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -18,6 +19,10 @@ namespace Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership; public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy { private readonly IUnitOfWork _unitOfWork; + // The policy is registered per request, so this is a per-request cache keyed by the user that was loaded. It is not shared between requests, and the key prevents a reused policy instance from answering for a different user. + private Guid? _loadedUserId; + private bool _canAccessAllLibraries; + private HashSet _ownedLibraryIds = []; /// /// Initializes a new instance of the class. @@ -40,17 +45,24 @@ public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy if (context is not LibraryOwnershipPolicyContext libraryContext) return false; - // Admins can access any media library. - Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getUserResult.IsFailure || getUserResult.Value is null) - return false; - if (getUserResult.Value.UserRole?.Role.RoleName == "Admin") - return true; + // The policy is scoped to one request, so the user graph, including the libraries the user owns, is read once and every library of that request is answered from the same set. + if (_loadedUserId != userId) + { + Result getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getUserResult.IsFailure || getUserResult.Value is null) + { + _loadedUserId = userId; + _canAccessAllLibraries = false; + _ownedLibraryIds = []; + return false; + } + // Admins can access any media library. + _canAccessAllLibraries = getUserResult.Value.UserRole?.Role.RoleName == "Admin"; + // The user graph already carries the libraries owned by this user, so answering the policy needs no second library read. + _ownedLibraryIds = [.. getUserResult.Value.Libraries.Select(library => library.Id)]; + _loadedUserId = userId; + } - // Regular users can only access the media libraries they own. - Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure || getLibraryResult.Value is null) - return false; - return getLibraryResult.Value.UserId == userId; + return _canAccessAllLibraries || _ownedLibraryIds.Contains(libraryContext.LibraryId); } } diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs index 76fe9689..9d04b5a3 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/EventualConsistencyMiddleware.cs @@ -1,19 +1,20 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; -using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Exceptions; using Lumina.Presentation.Api.Common.Http; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; +using System; +using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.Common.Middlewares; /// -/// Middleware that ensures eventual consistency by handling domain events and publishing them after the request has completed successfully. +/// Middleware that owns the request transaction, committing it and publishing the queued domain events after a successful request, and rolling it back otherwise. /// public class EventualConsistencyMiddleware { @@ -36,9 +37,9 @@ public class EventualConsistencyMiddleware /// /// The current HTTP context. /// The domain event publisher used to publish events. - /// The database context used to manage the transaction. + /// Injected unit of work that owns the request transaction. /// In memory queue containing the queued domain events. - public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, LuminaDbContext dbContext, IDomainEventsQueue domainEventQueue) + public async Task InvokeAsync(HttpContext context, IDomainEventPublisher domainEventPublisher, IUnitOfWork unitOfWork, IDomainEventsQueue domainEventQueue) { // Endpoints that serve long lived responses (for example a track stream) opt out through endpoint metadata, so that their response never // holds the request's database transaction open; the opt out is metadata based, so it follows the endpoint even when its route changes. @@ -48,24 +49,27 @@ public class EventualConsistencyMiddleware return; } - // begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation - IDbContextTransaction transaction = await dbContext.Database.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); - // register an action to be executed once the response is completed (the user already received a response for the request) + // Begin a new database transaction - this will wrap any database operations performed during this HTTP request in an atomic operation. + await unitOfWork.BeginTransactionAsync(context.RequestAborted).ConfigureAwait(false); + // Register an action to be executed once the response is completed (the user already received a response for the request). context.Response.OnCompleted(async () => { try { - // only proceed if the response status code indicates success + // Only proceed if the response status code indicates success. The request abort token is deliberately not consulted here: + // it can already be cancelled when the callback runs, even though the operation completed successfully, and refusing to + // commit then would discard a write whose success response was already sent. An aborted request is instead reported as a + // non-success status by the exception handling middleware. if (context.Response.StatusCode >= 200 && context.Response.StatusCode < 300) { - // commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are + // Commit the transaction: because some domain events trigger jobs that end up being processed in background hosted services, and those are // singletons that require their own DI scope to be created, any changes made on the DbContext in this HTTP scope would not be seen on the // DbContext created in the background service scope, because the transaction is not yet committed here; therefor, the transaction needs to be - // committed first, before any domain events are fired - // see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0002.md for details: - await transaction.CommitAsync().ConfigureAwait(false); + // committed first, before any domain events are fired. + // See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0002.md for details: + await unitOfWork.CommitTransactionAsync(CancellationToken.None).ConfigureAwait(false); - // check if domain events exist in the channel queue and publish them + // Check if domain events exist in the channel queue and publish them. while (domainEventQueue.TryDequeue(out IDomainEvent? nextEvent)) await domainEventPublisher.PublishAsync(nextEvent); } @@ -74,10 +78,23 @@ public class EventualConsistencyMiddleware { _logger.LogCritical(ex, "Failed to perform eventual consistency"); } + catch (Exception ex) // The response is already complete, so this failure cannot reach the client. It is logged, and the transaction is still closed by the rollback below. + { + _logger.LogError(ex, "Failed to complete the request transaction for {Path}", context.Request.Path); + } finally { - // DisposeAsync automatically roles back any changes, if a call to CommitAsync was not performed prior - await transaction.DisposeAsync().ConfigureAwait(false); + // A commit or a rollback clears the transaction, so this only closes one that the failure above left open. It runs for + // every response, including the non-success one that never attempted a commit. Rollback must never throw out of the + // completion callback, and must never mask the failure that is already being handled. + try + { + await unitOfWork.RollbackTransactionAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to roll back the request transaction for {Path}", context.Request.Path); + } } }); await _next(context).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs index d24f2e22..ec7ac12a 100644 --- a/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Lumina.Presentation.Api/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -41,12 +41,16 @@ public class ExceptionHandlingMiddleware } catch (OperationCanceledException) { - // the request was aborted, so there is no client left to write a response to + // The request was aborted, so there is no client left to write a response to. The status is still set to a non-success value, + // because the eventual consistency middleware decides whether to commit from it, and the writes of an aborted request must be + // rolled back instead of being reported as a success. + if (!context.Response.HasStarted) + context.Response.StatusCode = StatusCodes.Status499ClientClosedRequest; throw; } catch (Exception ex) { - // once the response has started, it is no longer possible to replace it with a ProblemDetails response + // Once the response has started, it is no longer possible to replace it with a ProblemDetails response. if (context.Response.HasStarted) throw; _logger.LogError(ex, "Unhandled exception occurred while processing request {Method} {Path}", context.Request.Method, context.Request.Path); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs b/src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs new file mode 100644 index 00000000..6c26c625 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/Routes/Playlists/ApiRoutes.Playlists.cs @@ -0,0 +1,24 @@ +namespace Lumina.Presentation.Api.Common.Routes.Playlists; + +/// +/// Class for the collection of the playlist routes of the API. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the playlists of the current user. + /// + public static class Playlists + { + public const string GET_PLAYLISTS = "/users/me/playlists"; + public const string CREATE_PLAYLIST = "/users/me/playlists"; + public const string GET_PLAYLIST = "/users/me/playlists/{playlistId}"; + public const string UPDATE_PLAYLIST = "/users/me/playlists/{playlistId}"; + public const string DELETE_PLAYLIST = "/users/me/playlists/{playlistId}"; + public const string ADD_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries"; + public const string ADD_PLAYLIST_ENTRIES = "/users/me/playlists/{playlistId}/entries-batch"; + public const string ADD_PLAYLIST_SCOPE_ENTRIES = "/users/me/playlists/{playlistId}/entries-scope"; + public const string REMOVE_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + public const string MOVE_PLAYLIST_ENTRY = "/users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs new file mode 100644 index 00000000..dc09756a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.AddPlaylistEntries; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries-batch route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddPlaylistEntriesEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addPlaylistEntriesCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add playlist entries commands. + public AddPlaylistEntriesEndpoint(ICommandHandler> addPlaylistEntriesCommandHandler) + { + _addPlaylistEntriesCommandHandler = addPlaylistEntriesCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRIES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds several tracks to the end of the ordered entries of a playlist of the current user, in order. + /// + /// The request containing the tracks to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntriesRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _addPlaylistEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs new file mode 100644 index 00000000..28dfa0dc --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesEndpointSummary() + { + Summary = "Adds several tracks to a playlist of the current user."; + Description = "Adds several tracks to the end of the ordered entries of the playlist identified by its Id, when the playlist belongs to the currently authenticated user, in the order the request lists them. Every track must exist, and the media library of every track must be reachable by the current user; a missing track and an unreachable library are both reported as not found, so the response never reveals whether a track exists in another user's library. The playlist must accept music tracks, which is the only media kind exposed until video libraries are catalogued. The same track may appear more than once. The request is applied as a whole: when any track is missing or not reachable, no entry is added. The tracks are inserted in bounded batches, so a long queue is accepted."; + + ExampleRequest = new AddPlaylistEntriesRequest( + TrackIds: + [ + Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + Guid.Parse("8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b") + ] + ); + RequestParam(request => request.TrackIds, "The Ids of the tracks to add, in the order they must take. Required."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entries were added to."); + ResponseParam(response => response.AddedCount, "The number of entries that were appended, including repeated tracks."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The number of added entries is returned with the playlist activity time.", + example: new PlaylistEntriesAddedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + AddedCount: 12, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch" + } + } + ); + + Response(403, "The request failed because the playlist does not accept music tracks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "PlaylistDoesNotAcceptMediaItems", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the playlist does not exist, does not belong to the current user, or a track does not exist or is not reachable.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the entries could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-batch", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs new file mode 100644 index 00000000..dfadfa40 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.AddPlaylistEntry; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddPlaylistEntryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addPlaylistEntryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add playlist entry commands. + public AddPlaylistEntryEndpoint(ICommandHandler> addPlaylistEntryCommandHandler) + { + _addPlaylistEntryCommandHandler = addPlaylistEntryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds a track to the end of the ordered entries of a playlist of the current user. + /// + /// The request containing the track to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _addPlaylistEntryCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..39915404 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs @@ -0,0 +1,181 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryEndpointSummary() + { + Summary = "Adds a track to a playlist of the current user."; + Description = "Adds a track to the end of the ordered entries of the playlist identified by its Id, when the playlist belongs to the currently authenticated user. The track must exist, and its media library must be reachable by the current user; a missing track and an unreachable library are both reported as not found, so the response never reveals whether a track exists in another user's library. The playlist must accept music tracks, which is the only media kind exposed until video libraries are catalogued. The same track may appear in a playlist more than once."; + + ExampleRequest = new AddPlaylistEntryRequest( + TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f") + ); + RequestParam(request => request.TrackId, "The Id of the track to add. Required."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entry was added to."); + ResponseParam(response => response.Entry, "The added entry."); + ResponseParam(response => response.Entry.Id, "The Id of the added entry."); + ResponseParam(response => response.Entry.MediaItemId, "The Id of the media item the entry references."); + ResponseParam(response => response.Entry.MediaItemType, "The kind of media item the entry references."); + ResponseParam(response => response.Entry.Position, "The zero based position of the entry in the playlist."); + ResponseParam(response => response.Entry.LibraryId, "The Id of the media library that contains the media item."); + ResponseParam(response => response.Entry.CollectionId, "The Id of the collection that contains the media item."); + ResponseParam(response => response.Entry.CreatorId, "The Id of the creator of the media item."); + ResponseParam(response => response.Entry.MediaItemTitle, "The title of the media item."); + ResponseParam(response => response.Entry.CollectionTitle, "The title of the collection that contains the media item."); + ResponseParam(response => response.Entry.CreatorName, "The name of the creator of the media item."); + ResponseParam(response => response.Entry.DurationInSeconds, "The duration of the media item in seconds."); + ResponseParam(response => response.Entry.CoverPath, "The path of the cover art of the collection, if available."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated."); + + Response(200, "The added entry is returned with the playlist activity time.", + example: new PlaylistEntryAddedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Entry: new PlaylistEntryResponse( + Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaItemType: PlaylistMediaItemType.MusicTrack, + Position: 11, + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"), + CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + MediaItemTitle: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + DurationInSeconds: 262, + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" + ), + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries" + } + } + ); + + Response(403, "The request failed because the playlist does not accept music tracks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Forbidden", + status = 403, + detail = "PlaylistDoesNotAcceptMediaItems", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the playlist does not exist, does not belong to the current user, or the track does not exist or is not reachable.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because the entry could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "TrackIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs new file mode 100644 index 00000000..b1d734cb --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.AddPlaylistScopeEntries; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries-scope route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class AddPlaylistScopeEntriesEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _addPlaylistScopeEntriesCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling add playlist scope entries commands. + public AddPlaylistScopeEntriesEndpoint(ICommandHandler> addPlaylistScopeEntriesCommandHandler) + { + _addPlaylistScopeEntriesCommandHandler = addPlaylistScopeEntriesCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES); + Version(1); + DontCatchExceptions(); + } + + /// + /// Adds every track of a music library, an artist or an album to a playlist of the current user. + /// + /// The request containing the scope whose tracks are appended. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistScopeEntriesRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _addPlaylistScopeEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs new file mode 100644 index 00000000..2e5ef145 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesEndpointSummary() + { + Summary = "Adds every track of a library, artist or album to a playlist of the current user."; + Description = "Appends every track of the music library identified by libraryId, optionally limited to an artist or an album, to the end of the ordered entries of the playlist identified by its Id. The server resolves the scope in catalogue order with one set-based statement, so a whole library is appended without materializing its track Ids, sorting them in memory or sending them to the data access layer. The playlist must belong to the currently authenticated user, and the library must be reachable by the current user. An empty scope appends nothing and reports a zero count without an activity time. The same track may appear in a playlist more than once."; + + ExampleRequest = new AddPlaylistScopeEntriesRequest( + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f") + ); + RequestParam(request => request.LibraryId, "The Id of the music library the scope belongs to. Required."); + RequestParam(request => request.ArtistId, "The Id of the artist the scope is limited to. Optional."); + RequestParam(request => request.AlbumId, "The Id of the album the scope is limited to. Optional."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entries were added to."); + ResponseParam(response => response.AddedCount, "The number of entries that were appended, including repeated tracks."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The scope was appended to the playlist.", + example: new PlaylistEntriesAddedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + AddedCount: 120, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope" + } + } + ); + + Response(403, "The request failed because the library is not accessible to the current user.", "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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(409, "The request failed because the entries could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries-scope", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs new file mode 100644 index 00000000..67518137 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.CreatePlaylist; + +/// +/// API endpoint for the /users/me/playlists route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class CreatePlaylistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _createPlaylistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling create playlist commands. + public CreatePlaylistEndpoint(ICommandHandler> createPlaylistCommandHandler) + { + _createPlaylistCommandHandler = createPlaylistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.POST); + Routes(ApiRoutes.Playlists.CREATE_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Creates a playlist of the current user. + /// + /// The request containing the details of the playlist to create. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CreatePlaylistRequest request, CancellationToken cancellationToken) + { + Result result = await _createPlaylistCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..ac0d1a5e --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistEndpointSummary() + { + Summary = "Creates a playlist of the current user."; + Description = "Creates a playlist that belongs to the currently authenticated user. The name is required, while the description is optional. The type decides which media items the playlist accepts. Only the music type is exposed, because video libraries are not catalogued yet; the entry model and the storage already carry a generic media item kind, so exposing video playlists later does not require a schema change. The new playlist starts empty."; + + ExampleRequest = new CreatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + RequestParam(request => request.Type, "The kind of media the playlist holds. Required. Only Music is currently supported."); + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.Entries, "The ordered entries of the playlist."); + ResponseParam(response => response.EntryCount, "The total number of entries the playlist holds, even when only a window of them is returned."); + ResponseParam(response => response.CreatedOnUtc, "The date and time when the playlist was created."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The playlist was created and is returned.", + example: new PlaylistResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + Entries: [], + EntryCount: 0, + CreatedOnUtc: new DateTime(2026, 10, 21, 12, 0, 0, DateTimeKind.Utc), + UpdatedOnUtc: null + ) + ); + + 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/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists" + } + } + ); + + Response(409, "The request failed because the playlist could not be stored, because of a conflicting row or because the database is busy.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "UniqueConstraintViolation", + instance = "/api/v1/users/me/playlists", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists", + 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/users/me/playlists", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistNameCannotBeEmpty", + "PlaylistNameMustBeMaximum255CharactersLong", + "PlaylistDescriptionMustBeMaximum2000CharactersLong", + "PlaylistTypeIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs new file mode 100644 index 00000000..d66f2881 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.DeletePlaylist; + +/// +/// API endpoint for the /users/me/playlists/{playlistId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class DeletePlaylistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _deletePlaylistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling delete playlist commands. + public DeletePlaylistEndpoint(ICommandHandler> deletePlaylistCommandHandler) + { + _deletePlaylistCommandHandler = deletePlaylistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Playlists.DELETE_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Deletes a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifier from the route. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _deletePlaylistCommandHandler.HandleAsync(new DeletePlaylistCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs new file mode 100644 index 00000000..39c4a706 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistEndpointSummary() + { + Summary = "Deletes a playlist of the current user."; + Description = "Deletes the playlist identified by its Id when it belongs to the currently authenticated user, together with its ordered entries. The tracks it referenced are not deleted, because a playlist only references them by Id."; + + Response(200, "The playlist 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + } + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + errors = new Dictionary + { + { "General.Validation", new[] { "PlaylistIdCannotBeEmpty" } } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs new file mode 100644 index 00000000..fbdf19e6 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Queries.GetPlaylist; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// API endpoint for the /users/me/playlists/{playlistId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetPlaylistEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaylistQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playlist queries. + public GetPlaylistEndpoint(IQueryHandler> getPlaylistQueryHandler) + { + _getPlaylistQueryHandler = getPlaylistQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.Playlists.GET_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets a window of the entries of a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist belongs to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // Take the unique identifier from the route. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + int offset = request.Offset ?? 0; + // The limit bounds one response window, not the size of the playlist. Clamping it keeps a crafted limit from turning the + // windowed read into one unbounded response, while the handler still validates the value independently. + int limit = Math.Clamp(request.Limit ?? PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE, 1, PlaylistWindow.MAXIMUM_ENTRY_WINDOW_SIZE); + Result result = await _getPlaylistQueryHandler + .HandleAsync(new GetPlaylistQuery(playlistId, offset, limit), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs new file mode 100644 index 00000000..32df1afd --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistEndpointSummary() + { + Summary = "Gets a playlist of the current user."; + Description = "Gets the playlist identified by its Id when it belongs to the currently authenticated user, together with a window of its ordered entries. The offset and limit query parameters select the window, and entryCount reports the total number of entries. The limit is a response-window bound of at most 1000 entries and does not cap the size of the playlist. Each entry carries the media item Id and the media item kind it references, and a music track also carries the display details needed to play it: the library, album and artist Ids, the title, the album title, the artist name, the duration and the cover art. An entry whose media item was deleted is still returned, with empty display details."; + + ExampleRequest = new GetPlaylistRequest( + Offset: 0, + Limit: 200 + ); + RequestParam(request => request.Offset, "The zero based position of the first entry to return. Optional; defaults to 0."); + RequestParam(request => request.Limit, "The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200."); + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.Entries, "The ordered entries of the playlist."); + ResponseParam(response => response.EntryCount, "The total number of entries the playlist holds, even when only a window of them is returned."); + ResponseParam(response => response.CreatedOnUtc, "The date and time when the playlist was created."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The playlist and its ordered entries are returned.", + example: new PlaylistResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + Entries: + [ + new PlaylistEntryResponse( + Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + MediaItemType: PlaylistMediaItemType.MusicTrack, + Position: 0, + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"), + CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + MediaItemTitle: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + DurationInSeconds: 262, + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg" + ) + ], + EntryCount: 1, + CreatedOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc), + UpdatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + } + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistEntryWindowOffsetIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs new file mode 100644 index 00000000..1fe5f1ab --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Queries.GetPlaylists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.GetPlaylists; + +/// +/// API endpoint for the /users/me/playlists route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class GetPlaylistsEndpoint : BaseEndpoint +{ + private readonly IQueryHandler> _getPlaylistsQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get playlists queries. + public GetPlaylistsEndpoint(IQueryHandler> getPlaylistsQueryHandler) + { + _getPlaylistsQueryHandler = getPlaylistsQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.GET); + Routes(ApiRoutes.Playlists.GET_PLAYLISTS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the playlists of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + Result result = await _getPlaylistsQueryHandler.HandleAsync(new GetPlaylistsQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs new file mode 100644 index 00000000..baf48137 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsEndpointSummary() + { + Summary = "Gets the playlists of the current user."; + Description = "Gets the playlists that belong to the currently authenticated user, ordered by their most recent activity. Each playlist is returned without its entries, together with the number of entries it holds. A playlist of another user is never returned."; + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.EntryCount, "The number of entries of the playlist."); + ResponseParam(response => response.CreatedOnUtc, "The date and time when the playlist was created."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The playlists of the current user are returned.", + example: new[] + { + new PlaylistSummaryResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + EntryCount: 12, + CreatedOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc), + UpdatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc) + ) + } + ); + + 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/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists" + } + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..86de9a8b --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.MovePlaylistEntry; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries/{playlistEntryId}/move route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class MovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _movePlaylistEntryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling move playlist entry commands. + public MovePlaylistEntryEndpoint(ICommandHandler> movePlaylistEntryCommandHandler) + { + _movePlaylistEntryCommandHandler = movePlaylistEntryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Playlists.MOVE_PLAYLIST_ENTRY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Moves one entry of a playlist of the current user to a new position. + /// + /// The request containing the new position of the entry. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(MovePlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlist and the entry are identified by the route values, not by any id posted in the body. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + string? playlistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString(); + Result result = await _movePlaylistEntryCommandHandler.HandleAsync(request.ToCommand(playlistId, playlistEntryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..ad434da2 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryEndpointSummary() + { + Summary = "Moves one entry of a playlist of the current user."; + Description = "Moves the entry identified by its Id to the target zero based position in the ordered entries of the playlist identified by its Id, when the playlist belongs to the currently authenticated user. The request carries only the target position, so the move changes one sparse order key instead of rewriting the following entries. The moved entry and its new position are returned."; + + ExampleRequest = new MovePlaylistEntryRequest( + TargetPosition: 3 + ); + RequestParam(request => request.TargetPosition, "The new zero based position of the entry. Required, zero or greater."); + + ResponseParam(response => response.PlaylistId, "The Id of the playlist whose entry was moved."); + ResponseParam(response => response.EntryId, "The Id of the moved entry."); + ResponseParam(response => response.Position, "The new zero based position of the entry."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated."); + + Response(200, "The moved entry and its new position are returned.", + example: new PlaylistEntryMovedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + EntryId: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + Position: 3, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move" + } + } + ); + + Response(404, "The request failed because the playlist or the entry does not exist, or the playlist does not belong to the current user.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistEntryNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read, or because the new position could not be stored.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d/move", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistEntryIdCannotBeEmpty", + "PlaylistMoveTargetPositionIsInvalid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..2cbf9ff8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.RemovePlaylistEntry; + +/// +/// API endpoint for the /users/me/playlists/{playlistId}/entries/{playlistEntryId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class RemovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _removePlaylistEntryCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling remove playlist entry commands. + public RemovePlaylistEntryEndpoint(ICommandHandler> removePlaylistEntryCommandHandler) + { + _removePlaylistEntryCommandHandler = removePlaylistEntryCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.DELETE); + Routes(ApiRoutes.Playlists.REMOVE_PLAYLIST_ENTRY); + Version(1); + DontCatchExceptions(); + } + + /// + /// Removes an entry from a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // Take the unique identifiers from the route. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + string? playlistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString(); + Result result = await _removePlaylistEntryCommandHandler.HandleAsync(new RemovePlaylistEntryCommand(playlistId, playlistEntryId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..f66ea768 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryEndpointSummary() + { + Summary = "Removes an entry from a playlist of the current user."; + Description = "Removes the entry identified by its Id from the playlist identified by its Id, when the playlist belongs to the currently authenticated user. The entries use sparse order keys, so only the removed row is written and no remaining entry needs to be repositioned. The referenced track is not deleted."; + + ResponseParam(response => response.PlaylistId, "The Id of the playlist the entry was removed from."); + ResponseParam(response => response.RemovedEntryId, "The Id of the removed entry."); + ResponseParam(response => response.RepositionedCount, "Always zero, because sparse order keys need no remaining entries to be repositioned."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated."); + + Response(200, "The removed entry and the number of repositioned entries are returned.", + example: new PlaylistEntryRemovedResponse( + PlaylistId: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + RemovedEntryId: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"), + RepositionedCount: 0, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d" + } + } + ); + + Response(404, "The request failed because the playlist or the entry does not exist, or the playlist does not belong to the current user.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistEntryNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b/entries/2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistEntryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs new file mode 100644 index 00000000..6f828fa4 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Playlists; +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.Playlists.UpdatePlaylist; + +/// +/// API endpoint for the /users/me/playlists/{playlistId} route. +/// +/// +/// Uses "me" because it is always for the currently authenticated user. +/// +public class UpdatePlaylistEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _updatePlaylistCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling update playlist commands. + public UpdatePlaylistEndpoint(ICommandHandler> updatePlaylistCommandHandler) + { + _updatePlaylistCommandHandler = updatePlaylistCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Playlists.UPDATE_PLAYLIST); + Version(1); + DontCatchExceptions(); + } + + /// + /// Updates the details of a playlist of the current user. + /// + /// The request containing the new details of the playlist. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body, so that a mismatched id can never redirect the + // update to another playlist. + string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); + Result result = await _updatePlaylistCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..c0215763 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistEndpointSummary() + { + Summary = "Updates the details of a playlist of the current user."; + Description = "Updates the name and the description of the playlist identified by its Id when it belongs to the currently authenticated user, leaving its ordered entries untouched. The playlist is identified by the route value, not by any id posted in the body."; + + ExampleRequest = new UpdatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day." + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + + ResponseParam(response => response.Id, "The Id of the playlist."); + ResponseParam(response => response.Name, "The name of the playlist."); + ResponseParam(response => response.Description, "The description of the playlist, if applicable."); + ResponseParam(response => response.Type, "The kind of media the playlist holds."); + ResponseParam(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable."); + + Response(200, "The updated playlist scalars are returned.", + example: new PlaylistDetailsResponse( + Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"), + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music, + UpdatedOnUtc: new DateTime(2026, 10, 20, 12, 0, 0, DateTimeKind.Utc) + ) + ); + + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token has expired", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b" + } + } + ); + + Response(404, "The request failed because the playlist does not exist, or it does not belong to the current user.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaylistNotFound", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(409, "The request failed because another request changed the playlist after it was read.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "ConcurrencyConflict", + instance = "/api/v1/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + 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/users/me/playlists/1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "PlaylistIdCannotBeEmpty", + "PlaylistNameCannotBeEmpty", + "PlaylistNameMustBeMaximum255CharactersLong", + "PlaylistDescriptionMustBeMaximum2000CharactersLong" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index eb65b3e3f3f3ab49d63324f199943b02d3af5291..8bccca6070961f60f20e09f792e668373a72e29a 100644 GIT binary patch delta 31281 zcmV(}K+wPXhZn?`7l4ETgaU*Egaot&pdgoH!vz$#(3Azb4jBUk6aWAK2mnZJR9$%= zW62>H007cq002Oju^rbsS9+EyI@_v;5h0w74q&emO>t87bTcLQkj8;=)paxE5Vq}0j5 zBCo1En=PU&-X6UCLcq_9C$pKT)>0JFN{U#fvXV+fWtFH(!HY7lS8D<|{eO5i6)LCC z%e>r(D65hgd|JtJE2{iTW+G8y5tU^kV{y4{${(#h8M^!Y(wsq5la({my4s|0qU{!5X zK#3Doq|x?BtjZ)lroXdFZhzoeC1+)RqmD#WSGjn;ERQuq3{w_)Rz*oBOL3D_z=4}w zAi`AS8H_)n!k2Xm*Tgzm%u8zcWz=3989K!pT*e0(5mvRx+N(v>b3LA|Czk)sy-+wcC%T#XiI*moX zTmqz?ky2*WNQoj>3G%$tRV^(=I(z<16eaz=gufPteAo(_n=OE@EIlZKTt9aJQyl*c zSt_$t8C^@5m844L!OOcl`fz{$;&A=kYmV5|+XECyoYGM9EOtqJa-d{XF4i-8V8jf& zbYRHHj5;T?4Gf0i#DC4~PtTqew+8~`W+B&k8p{&Jv5`hql`scteooXaS#)}FS)=yZ z-QXvtALd)5tQp9{#sIw>Xz#@#1MO%uFM;X#Y6Xmbe3L-rRKZNg@O7|dPy=pvk=MY= zG`f`OL0Ak>2M~O}3HNn-nabN^5dpPqmVkCEel$}Rn6cxKJbxe+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B zP7Kr-0!IBWN2E!L60#Os74~t_#olm2djm7Y5-cP+r$i`yBA%{_oPZUkw;sNFUdQ*If#n=fE(X~Yogh;3?B z5ITe;|L@0*ARvPOsu}-n|B&fHU*Jst`O6VGeRBi?{(lqxpWKfBqW_J`6#p;be{wva z{}1c`S2X!AaohL5EJD`*+2*c)03uKj5ZM0$|BdF7Awb-$%h<~&H1x*%^TL1t6 diff --git a/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip b/src/Lumina.Presentation.Api/Core/Themes/Bundled/lumina-default.zip index 7570f7477e9066e37734083e16630ca931e03996..b951e6a11d9b28cfa9f95b30264fe962fcfa6253 100644 GIT binary patch delta 31230 zcmV)9K*hh|gBPol7l4ETgaU*Egaot&*B-awk_FBV83P0q0000807z|AU3nj4$srg3 z0McOq06>?|tppX9|GxztmtcAY6Mt)S<2I7t^D8jU)Job&^32xmez3=ra^|t?y~)hn zc#_LrDizZrBr&E)E9RK(02S5TKNXgFDU7f3JOJsKgX!IM87jbee7HOo^$-yG8 zsyv%5qAcDXy!=AI&xU&ux z%VZH%NuGU1G6$mC767qM;uybOM`;aT@9zG9)LutbG{?4e(}Z$=e;^KZBRF7HZBsyr z6IG062b9MYND+$bOGDNj6){WVNo2#B;!bW?vk_`jRe1fJ`vwDd4J1PZt^;fMZR1D zq@IydX4OcEB3B9Wywg=JEk!ze{!A1l{k??07KeP;3YwcOfUYb(D1ux+cK}ly{|s3w zvsD>gOPH0UO69@JyF2=DfB)ie{oHGg*wott6iJ-YQ1dKyNqlmkWK=HJGkRde47+q- z$jFR3C$kLG^5}jDCERK;%@xOvmtbuw_sKZg-K_z{)hb zl<7fO3{VFUe7_0zb$gl0+hY*{wQQDvb}N1~Qx%x8$f*Y)>r*e|GT^UQZ34)sDJ}syx@

Ggz%V@Us2cEXoh?vglsFMT{&Y+L5c7buJs7*Z?$$z^%{V z_~AJ^HGdcj@DWFWaUO6mDyq7KLFe#DM|cs33Wm85Fp4_61Zl*_NeRPMpg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s!e;TTE+Z_af1wH6 z{CCX|X4H>Euw*DsK;Zq4^#5=){;T_U+L8Z{RDt;auXhOl9~GMKe^fjfe&Y}r(Es~l zE)x)#=#a?}Anw){4i=2IZcdKMa-iSPK{6HyA#maUd&6pSM#~rkADC_~M8@tuI3eEu Zz&n)XARzyvG5WU&i9tYW3L*YQ{|}zuSor_| diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs new file mode 100644 index 00000000..fa47d0da --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDetailsDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +///

+/// Data transfer object for the editable scalars of a playlist after a details update. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}")] +public sealed record PlaylistDetailsDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs new file mode 100644 index 00000000..e6c22402 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistDto.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for a playlist together with its ordered entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries the playlist holds, even when only a window of them is returned. +/// The ordered entries of the requested window of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; Entries: {Entries.Count}")] +public sealed record PlaylistDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + List Entries, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs new file mode 100644 index 00000000..af9ccb81 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntriesAddedDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for the result of appending several tracks to a playlist. +/// +/// The Id of the playlist the entries were added to. +/// The number of entries that were appended, including repeated tracks. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; AddedCount: {AddedCount}")] +public sealed record PlaylistEntriesAddedDto( + Guid PlaylistId, + int AddedCount, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs new file mode 100644 index 00000000..b5c5a123 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryAddedDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for an entry appended to a playlist. +/// +/// The Id of the playlist the entry was added to. +/// The added entry. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; Entry: {Entry.Id}")] +public sealed record PlaylistEntryAddedDto( + Guid PlaylistId, + PlaylistEntryDto Entry, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs new file mode 100644 index 00000000..4265d2ff --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryDto.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for an ordered playlist entry together with the display details of the media item it references. +/// +/// The Id of the entry. +/// The Id of the media item referenced by the entry. +/// The kind of media item referenced by the entry. +/// The zero based position of the entry in the playlist. +/// The Id of the media library that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the collection that contains the media item, or an empty Guid when the item no longer exists. +/// The Id of the creator of the media item, or an empty Guid when the item no longer exists. +/// The title of the media item, or an empty string when the item no longer exists. +/// The title of the collection that contains the media item, or an empty string when the item no longer exists. +/// The name of the creator of the media item, or an empty string when the item no longer exists. +/// The duration of the media item in seconds, or zero when the item no longer exists. +/// The path of the cover art of the collection, if available. +[DebuggerDisplay("Id: {Id}; MediaItemId: {MediaItemId}; Position: {Position}")] +public sealed record PlaylistEntryDto( + Guid Id, + Guid MediaItemId, + PlaylistMediaItemType MediaItemType, + int Position, + Guid LibraryId, + Guid CollectionId, + Guid CreatorId, + string MediaItemTitle, + string CollectionTitle, + string CreatorName, + int DurationInSeconds, + string? CoverPath +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs new file mode 100644 index 00000000..4d0da515 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistEntryMovedDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for the result of moving one entry of a playlist to a new position. +/// +/// The Id of the playlist whose entry was moved. +/// The Id of the moved entry. +/// The new zero based position of the entry. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("PlaylistId: {PlaylistId}; EntryId: {EntryId}; Position: {Position}")] +public sealed record PlaylistEntryMovedDto( + Guid PlaylistId, + Guid EntryId, + int Position, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs new file mode 100644 index 00000000..46af5da3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Playlists/PlaylistSummaryDto.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Playlists; + +/// +/// Data transfer object for a playlist in a list, without its entries. +/// +/// The Id of the playlist. +/// The name of the playlist. +/// The description of the playlist, if applicable. +/// The kind of media the playlist holds. +/// The number of entries of the playlist. +/// The date and time when the playlist was created. +/// The date and time when the playlist was last updated, if applicable. +[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}")] +public sealed record PlaylistSummaryDto( + Guid Id, + string Name, + string? Description, + PlaylistType Type, + int EntryCount, + DateTime CreatedOnUtc, + DateTime? UpdatedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs new file mode 100644 index 00000000..71f7dd80 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistMediaItemType.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media item an ordered playlist entry can reference. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistMediaItemType +{ + /// + /// An entry that references a music track. + /// + MusicTrack, + + /// + /// An entry that references a video file. + /// + VideoFile, +} diff --git a/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs new file mode 100644 index 00000000..978c044b --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Enums/Playlists/PlaylistType.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Enums.Playlists; + +/// +/// Enumeration for the kinds of media a playlist can hold. +/// +[DebuggerDisplay("{ToString()}")] +public enum PlaylistType +{ + /// + /// A playlist whose ordered entries reference music tracks. + /// + Music, +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs new file mode 100644 index 00000000..dd5a7729 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntriesRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for adding several tracks to a playlist of the current user, in order. +/// +/// The Ids of the tracks to add, in the order they must take. Required. +[DebuggerDisplay("TrackCount: {TrackIds.Count}")] +public record AddPlaylistEntriesRequest( + List? TrackIds +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs new file mode 100644 index 00000000..098c6ae1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistEntryRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for adding a track to a playlist of the current user. +/// +/// The Id of the track to add. Required. +[DebuggerDisplay("TrackId: {TrackId}")] +public record AddPlaylistEntryRequest( + Guid? TrackId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs new file mode 100644 index 00000000..96dcdde1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/AddPlaylistScopeEntriesRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request to add every track of a music library, an artist or an album to a playlist, resolved on the server. +/// +/// The Id of the music library the scope belongs to. Required. +/// The Id of the artist the scope is limited to. Optional. +/// The Id of the album the scope is limited to. Optional. +[DebuggerDisplay("LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")] +public record AddPlaylistScopeEntriesRequest( + Guid LibraryId, + Guid? ArtistId, + Guid? AlbumId +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs new file mode 100644 index 00000000..878159a4 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/CreatePlaylistRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for creating a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +/// The kind of media the playlist holds. Required. +[DebuggerDisplay("Name: {Name}")] +public record CreatePlaylistRequest( + string? Name, + string? Description, + PlaylistType? Type +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs new file mode 100644 index 00000000..7f39ba2a --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/GetPlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for getting a window of the entries of a playlist of the current user. +/// +/// The zero based position of the first entry to return. Optional; defaults to 0. +/// The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200. +[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")] +public record GetPlaylistRequest( + int? Offset, + int? Limit +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs new file mode 100644 index 00000000..7115dcd3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/MovePlaylistEntryRequest.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for moving one entry of a playlist of the current user to a new position. +/// +/// The new zero based position of the entry. Required. +[DebuggerDisplay("TargetPosition: {TargetPosition}")] +public record MovePlaylistEntryRequest( + int? TargetPosition +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs new file mode 100644 index 00000000..b1524751 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Playlists/UpdatePlaylistRequest.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Playlists; + +/// +/// Represents a request for updating the details of a playlist of the current user. +/// +/// The name of the playlist. Required. +/// The description of the playlist. Optional. +[DebuggerDisplay("Name: {Name}")] +public record UpdatePlaylistRequest( + string? Name, + string? Description +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs new file mode 100644 index 00000000..e698d4ed --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Playlists.cs @@ -0,0 +1,24 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of remote API routes called by this Web application. +/// +public static partial class ApiRoutes +{ + /// + /// Routes for the playlists endpoints of the remote API. + /// + public static class Playlists + { + public const string GET_PLAYLISTS = "users/me/playlists"; + public const string CREATE_PLAYLIST = "users/me/playlists"; + public const string GET_PLAYLIST = "users/me/playlists/{playlistId}"; + public const string UPDATE_PLAYLIST = "users/me/playlists/{playlistId}"; + public const string DELETE_PLAYLIST = "users/me/playlists/{playlistId}"; + public const string ADD_PLAYLIST_ENTRY = "users/me/playlists/{playlistId}/entries"; + public const string ADD_PLAYLIST_ENTRIES = "users/me/playlists/{playlistId}/entries-batch"; + public const string ADD_PLAYLIST_SCOPE_ENTRIES = "users/me/playlists/{playlistId}/entries-scope"; + public const string REMOVE_PLAYLIST_ENTRY = "users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + public const string MOVE_PLAYLIST_ENTRY = "users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs new file mode 100644 index 00000000..390a4fc6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Playlists.cs @@ -0,0 +1,27 @@ +namespace Lumina.Presentation.Web.Common.Routes; + +/// +/// Class for the collection of routes defined in the Web application. +/// +public static partial class WebRoutes +{ + /// + /// Routes for the playlist pages. + /// + public static class Playlists + { + public const string INDEX = "{culture}/playlists"; + public const string GET_PLAYLISTS = "{culture}/playlists/api-get-playlists"; + public const string CREATE_PLAYLIST = "{culture}/playlists/api-create-playlist"; + public const string ADD = "{culture}/playlists/item"; + public const string ITEM = "{culture}/playlists/item/{playlistId}"; + public const string GET_PLAYLIST = "{culture}/playlists/item/{playlistId}/api-get-playlist"; + public const string UPDATE_PLAYLIST = "{culture}/playlists/item/{playlistId}/api-update-playlist"; + public const string DELETE_PLAYLIST = "{culture}/playlists/item/{playlistId}/api-delete-playlist"; + public const string ADD_PLAYLIST_ENTRY = "{culture}/playlists/item/{playlistId}/entries/api-add-entry"; + public const string ADD_PLAYLIST_ENTRIES = "{culture}/playlists/item/{playlistId}/api-add-entries"; + public const string ADD_PLAYLIST_SCOPE_ENTRIES = "{culture}/playlists/item/{playlistId}/api-add-scope-entries"; + public const string REMOVE_PLAYLIST_ENTRY = "{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-remove-entry"; + public const string MOVE_PLAYLIST_ENTRY = "{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry"; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs new file mode 100644 index 00000000..e3a9921a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-add-entries route. +/// +public class AddPlaylistEntriesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddPlaylistEntriesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.ADD_PLAYLIST_ENTRIES); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Adds several tracks to a playlist of the current user, in order. + /// + /// The request containing the tracks to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntriesRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistEntriesAddedDto playlist = await _apiHttpClient + .PostAsync(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRIES.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs new file mode 100644 index 00000000..4d907f34 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesEndpointSummary() + { + Summary = "Adds several tracks to a playlist of the current user."; + Description = "Proxies the request that adds several tracks, in order, to a playlist to the API server. The audio player uses it to add its current queue to a playlist. The number of added entries and the playlist activity time are returned."; + + Params["playlistId"] = "The Id of the playlist to add the tracks to."; + + ExampleRequest = new AddPlaylistEntriesRequest( + TrackIds: + [ + Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + Guid.Parse("8e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b") + ] + ); + RequestParam(request => request.TrackIds, "The Ids of the tracks to add, in the order they must take. Required."); + + Response(200, "The tracks were added and the number of added entries is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs new file mode 100644 index 00000000..b29cf49d --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/entries/api-add-entry route. +/// +public class AddPlaylistEntryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddPlaylistEntryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Adds a track to a playlist of the current user. + /// + /// The request containing the track to add. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistEntryAddedDto playlist = await _apiHttpClient + .PostAsync(ApiRoutes.Playlists.ADD_PLAYLIST_ENTRY.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..e85c28ad --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryEndpointSummary() + { + Summary = "Adds a track to a playlist of the current user."; + Description = "Proxies the request that adds a track to a playlist to the API server. The added entry and the playlist activity time are returned."; + + Params["playlistId"] = "The Id of the playlist to add the track to."; + + ExampleRequest = new AddPlaylistEntryRequest( + TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f") + ); + RequestParam(request => request.TrackId, "The Id of the track to add. Required."); + + Response(200, "The track was added and the resulting entry is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs new file mode 100644 index 00000000..bbc1fe43 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-add-scope-entries route. +/// +public class AddPlaylistScopeEntriesEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public AddPlaylistScopeEntriesEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Adds every track of a music library, an artist or an album to a playlist of the current user. + /// + /// The request containing the scope whose tracks are appended. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(AddPlaylistScopeEntriesRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistEntriesAddedDto result = await _apiHttpClient + .PostAsync(ApiRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(result); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs new file mode 100644 index 00000000..ade6f211 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesEndpointSummary() + { + Summary = "Adds every track of a library, artist or album to a playlist of the current user."; + Description = "Proxies the request that appends every track of a music library, an artist or an album to a playlist to the API server, in catalogue order. The server resolves the scope in one set-based statement. An empty scope appends nothing and reports a zero count."; + + Params["playlistId"] = "The Id of the playlist to add the tracks to."; + + ExampleRequest = new AddPlaylistScopeEntriesRequest( + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), + AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f") + ); + RequestParam(request => request.LibraryId, "The Id of the music library the scope belongs to. Required."); + RequestParam(request => request.ArtistId, "The Id of the artist the scope is limited to. Optional."); + RequestParam(request => request.AlbumId, "The Id of the album the scope is limited to. Optional."); + + Response(200, "The scope was appended to the playlist and the number of added entries is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs new file mode 100644 index 00000000..67d28c48 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// API endpoint for the /{culture}/playlists/api-create-playlist route. +/// +public class CreatePlaylistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public CreatePlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.POST); + Routes(WebRoutes.Playlists.CREATE_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Creates a playlist of the current user. + /// + /// The request containing the details of the playlist to create. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(CreatePlaylistRequest request, CancellationToken cancellationToken) + { + PlaylistDto playlist = await _apiHttpClient.PostAsync(ApiRoutes.Playlists.CREATE_PLAYLIST, request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..7db08474 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistEndpointSummary() + { + Summary = "Creates a playlist of the current user."; + Description = "Proxies the request that creates a playlist of the current user to the API server. The new playlist starts empty."; + + ExampleRequest = new CreatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day.", + Type: PlaylistType.Music + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + RequestParam(request => request.Type, "The kind of media the playlist holds. Required. Only Music is currently supported."); + + Response(200, "The playlist was created and is returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs new file mode 100644 index 00000000..9fb09752 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-delete-playlist route. +/// +public class DeletePlaylistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public DeletePlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Playlists.DELETE_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Deletes a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) + { + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + await _apiHttpClient.DeleteAsync(ApiRoutes.Playlists.DELETE_PLAYLIST.Replace("{playlistId}", playlistId), cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs new file mode 100644 index 00000000..c4cc56a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointSummary.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistEndpointSummary() + { + Summary = "Deletes a playlist of the current user."; + Description = "Proxies the request that deletes a playlist and its entries to the API server. The tracks the playlist referenced are not deleted."; + + Params["playlistId"] = "The Id of the playlist to delete."; + + Response(200, "The playlist was deleted.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs new file mode 100644 index 00000000..6dbc18ff --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpoint.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-get-playlist route. +/// +public class GetPlaylistEndpoint : BaseEndpoint +{ + private const int DEFAULT_ENTRY_WINDOW_SIZE = 200; + private const int MAXIMUM_ENTRY_WINDOW_SIZE = 1000; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.GET_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Retrieves a window of the entries of a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetPlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist belongs to the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + int offset = request.Offset ?? 0; + // The web tier enforces the same response-window bound before forwarding, so a crafted value cannot make this proxy buffer an + // unbounded playlist response even if it never reaches the API validator. + int limit = Math.Clamp(request.Limit ?? DEFAULT_ENTRY_WINDOW_SIZE, 1, MAXIMUM_ENTRY_WINDOW_SIZE); + string url = ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?offset={offset}&limit={limit}"; + PlaylistDto playlist = await _apiHttpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs new file mode 100644 index 00000000..c2d5bd5f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistEndpointSummary() + { + Summary = "Gets a playlist of the current user."; + Description = "Proxies the request that gets a playlist and a window of its ordered entries to the API server."; + + Params["playlistId"] = "The Id of the playlist to get."; + + ExampleRequest = new GetPlaylistRequest( + Offset: 0, + Limit: 200 + ); + RequestParam(request => request.Offset, "The zero based position of the first entry to return. Optional; defaults to 0."); + RequestParam(request => request.Limit, "The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200."); + + Response(200, "The playlist and its ordered entries are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs new file mode 100644 index 00000000..b8be307e --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpoint.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// API endpoint for the /{culture}/playlists/api-get-playlists route. +/// +public class GetPlaylistsEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetPlaylistsEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.GET_PLAYLISTS); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Retrieves the playlists of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The playlists belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + PlaylistSummaryDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Playlists.GET_PLAYLISTS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs new file mode 100644 index 00000000..9f11437f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointSummary.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsEndpointSummary() + { + Summary = "Gets the playlists of the current user."; + Description = "Proxies the request that lists the playlists of the current user to the API server."; + + Response(200, "The playlists of the current user are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs new file mode 100644 index 00000000..1c10ab75 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpoint.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; + +/// +/// API endpoint for the /{culture}/playlists route. +/// +public class PlaylistsIndexViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Playlists.Index"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "playlists/index"; + + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public PlaylistsIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.INDEX); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Displays the playlists of the current user, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page shows the playlists of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The page creates and deletes playlists, which submit through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + string title = _localizer["Title"].Value; + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["getPlaylistsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLISTS) ?? string.Empty, + ["addUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ADD) ?? string.Empty, + ["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(System.Guid) }) ?? string.Empty, + ["deleteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, new { playlistId = default(System.Guid) }) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Playlists/Index.cshtml", viewData: new Dictionary { ["Title"] = title }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs new file mode 100644 index 00000000..67534ee7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class PlaylistsIndexViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public PlaylistsIndexViewEndpointSummary() + { + Summary = "Renders the playlists page."; + Description = "Renders the page that lists and deletes the playlists of the current user."; + + Response(200, "The playlists page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs new file mode 100644 index 00000000..42579d9a --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpoint.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// API endpoint for the /{culture}/playlists/item route. +/// +public class AddPlaylistViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Playlists.Item"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "playlists/item"; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public AddPlaylistViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.ADD); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Displays the page that creates a playlist of the current user, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page creates a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + + // The page submits through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + PlaylistDto playlist = new( + Id: Guid.Empty, + Name: string.Empty, + Description: null, + Type: PlaylistType.Music, + EntryCount: 0, + Entries: [], + CreatedOnUtc: default, + UpdatedOnUtc: null + ); + string title = _localizer["CreatePlaylist"].Value; + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = title, + Description = string.Empty, + PageData = new Dictionary + { + ["isNew"] = true, + ["playlistId"] = playlist.Id.ToString(), + ["playlistJson"] = JsonSerializer.Serialize(playlist, s_camelCaseJsonOptions), + ["createPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST) ?? string.Empty, + ["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(Guid) }) ?? string.Empty, + ["getEnabledLibrariesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES) ?? string.Empty, + ["getArtistsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS) ?? string.Empty, + ["getArtistAlbumsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, new { artistId = default(Guid) }) ?? string.Empty, + ["getAlbumTracksUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty, + ["indexUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Playlists/Item.cshtml", playlist, new Dictionary { ["Title"] = title, ["IsNew"] = true }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title, ["IsNew"] = true }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs new file mode 100644 index 00000000..9737beaf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/AddPlaylistViewEndpointSummary.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistViewEndpointSummary() + { + Summary = "Renders the create playlist page."; + Description = "Renders the page that creates a playlist of the current user."; + + Response(200, "The create playlist page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs new file mode 100644 index 00000000..355452d0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpoint.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Lumina.Presentation.Web.Core.Themes; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId} route. +/// +public class PlaylistItemViewEndpoint : BaseEndpoint +{ + // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath. + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Playlists.Item"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope. + private const string VIEW_PAGE_KEY = "playlists/item"; + // The page renders one window at a time; the client asks for the next window through getPlaylistUrl. + private const int ENTRY_WINDOW_SIZE = 200; + + private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly IApiHttpClient _apiHttpClient; + private readonly IUrlService _urlService; + private readonly ThemePageRenderer _themePageRenderer; + private readonly IAntiforgery _antiforgery; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected service for rendering themed pages. + /// Injected service for anti-forgery token handling. + /// Injected factory used to create the localizer of the view resources. + public PlaylistItemViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory) + { + _apiHttpClient = apiHttpClient; + _urlService = urlService; + _themePageRenderer = themePageRenderer; + _antiforgery = antiforgery; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Playlists.ITEM); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + } + + /// + /// Displays a playlist of the current user, rendered by the active theme with a fallback to the Razor view. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The page shows a playlist of the authenticated user, so no intermediary may store it, and the response varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Cookie"; + // The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape + // its URL segment, and an unparseable id is reported by the API as a missing playlist id. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistDto playlist = await _apiHttpClient + .GetAsync( + ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?offset=0&limit={ENTRY_WINDOW_SIZE}", + cancellationToken).ConfigureAwait(false); + + // The page edits, reorders and deletes the playlist, which submit through the form anti-forgery token, so a fresh token is issued for it. + AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext); + + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = playlist.Name, + Description = playlist.Description ?? string.Empty, + PageData = new Dictionary + { + ["isNew"] = false, + ["playlistId"] = playlist.Id.ToString(), + ["playlistJson"] = JsonSerializer.Serialize(playlist, s_camelCaseJsonOptions), + ["entriesWindowSize"] = ENTRY_WINDOW_SIZE, + ["createPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST) ?? string.Empty, + ["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(Guid) }) ?? string.Empty, + ["getPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty, + ["updatePlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.UPDATE_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty, + ["deletePlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty, + ["addEntryUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY, new { playlistId = playlist.Id }) ?? string.Empty, + ["removeEntryUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.REMOVE_PLAYLIST_ENTRY, new { playlistId = playlist.Id, playlistEntryId = default(Guid) }) ?? string.Empty, + ["moveEntryUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.MOVE_PLAYLIST_ENTRY, new { playlistId = playlist.Id, playlistEntryId = default(Guid) }) ?? string.Empty, + ["getEnabledLibrariesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES) ?? string.Empty, + ["getArtistsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS) ?? string.Empty, + ["getArtistAlbumsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTIST_ALBUMS, new { artistId = default(Guid) }) ?? string.Empty, + ["getAlbumTracksUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ALBUM_TRACKS, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty, + ["indexUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX) ?? string.Empty, + ["antiforgeryToken"] = antiforgeryTokens.RequestToken, + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Playlists/Item.cshtml", playlist, new Dictionary { ["Title"] = playlist.Name, ["IsNew"] = false }); + + return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = playlist.Name, ["IsNew"] = false }); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs new file mode 100644 index 00000000..95bd4264 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/Item/PlaylistItemViewEndpointSummary.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.Item; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class PlaylistItemViewEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public PlaylistItemViewEndpointSummary() + { + Summary = "Renders a playlist page."; + Description = "Renders the page that edits, reorders, plays and deletes a playlist of the current user."; + + Params["playlistId"] = "The Id of the playlist to display."; + + Response(200, "The playlist page is rendered."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..23a17363 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry route. +/// +public class MovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public MovePlaylistEntryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Playlists.MOVE_PLAYLIST_ENTRY); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Moves one entry of a playlist of the current user to a new position. + /// + /// The request containing the new position of the entry. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(MovePlaylistEntryRequest request, CancellationToken cancellationToken) + { + // The playlist and the entry are identified by the route values, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + string routePlaylistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString() ?? string.Empty; + string playlistEntryId = Guid.TryParse(routePlaylistEntryId, out Guid parsedPlaylistEntryId) ? parsedPlaylistEntryId.ToString() : Guid.Empty.ToString(); + PlaylistEntryMovedDto entry = await _apiHttpClient + .PutAsync( + ApiRoutes.Playlists.MOVE_PLAYLIST_ENTRY + .Replace("{playlistId}", playlistId) + .Replace("{playlistEntryId}", playlistEntryId), + request, + cancellationToken).ConfigureAwait(false); + return JsonSuccess(entry); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..5faea45b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryEndpointSummary() + { + Summary = "Moves one entry of a playlist of the current user."; + Description = "Proxies the request that moves one entry of a playlist to a new position to the API server. The moved entry and its new position are returned."; + + Params["playlistId"] = "The Id of the playlist whose entry is moved."; + Params["playlistEntryId"] = "The Id of the entry to move."; + + ExampleRequest = new MovePlaylistEntryRequest( + TargetPosition: 3 + ); + RequestParam(request => request.TargetPosition, "The new zero based position of the entry. Required, zero or greater."); + + Response(200, "The moved entry and its new position are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs new file mode 100644 index 00000000..98de3a80 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/entries/{playlistEntryId}/api-remove-entry route. +/// +public class RemovePlaylistEntryEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public RemovePlaylistEntryEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.DELETE); + Routes(WebRoutes.Playlists.REMOVE_PLAYLIST_ENTRY); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Removes an entry from a playlist of the current user. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + string routePlaylistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString() ?? string.Empty; + string playlistEntryId = Guid.TryParse(routePlaylistEntryId, out Guid parsedPlaylistEntryId) ? parsedPlaylistEntryId.ToString() : Guid.Empty.ToString(); + await _apiHttpClient.DeleteAsync( + ApiRoutes.Playlists.REMOVE_PLAYLIST_ENTRY + .Replace("{playlistId}", playlistId) + .Replace("{playlistEntryId}", playlistEntryId), + cancellationToken).ConfigureAwait(false); + return JsonSuccess(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs new file mode 100644 index 00000000..970f6a7c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointSummary.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryEndpointSummary() + { + Summary = "Removes an entry from a playlist of the current user."; + Description = "Proxies the request that removes an entry from a playlist to the API server. The page removes the row from its current window without reading the playlist back."; + + Params["playlistId"] = "The Id of the playlist the entry belongs to."; + Params["playlistEntryId"] = "The Id of the entry to remove."; + + Response(200, "The entry was removed.", + example: new SuccessResponse(true) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs new file mode 100644 index 00000000..4b848a25 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// API endpoint for the /{culture}/playlists/item/{playlistId}/api-update-playlist route. +/// +public class UpdatePlaylistEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public UpdatePlaylistEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.PUT); + Routes(WebRoutes.Playlists.UPDATE_PLAYLIST); + DontAutoTag(); + Options(options => options.WithTags("Playlists")); + EnableAntiforgery(); + } + + /// + /// Updates the details of a playlist of the current user. + /// + /// The request containing the new details of the playlist. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(UpdatePlaylistRequest request, CancellationToken cancellationToken) + { + // The playlist is identified by the route value, not by any id posted in the body. + string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty; + string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString(); + PlaylistDetailsDto playlist = await _apiHttpClient + .PutAsync(ApiRoutes.Playlists.UPDATE_PLAYLIST.Replace("{playlistId}", playlistId), request, cancellationToken).ConfigureAwait(false); + return JsonSuccess(playlist); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs new file mode 100644 index 00000000..17b9b811 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointSummary.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistEndpointSummary() + { + Summary = "Updates the details of a playlist of the current user."; + Description = "Proxies the request that updates the name and description of a playlist to the API server. The ordered entries of the playlist are left untouched."; + + Params["playlistId"] = "The Id of the playlist to update."; + + ExampleRequest = new UpdatePlaylistRequest( + Name: "Evening listening", + Description: "Quiet tracks for the end of the day." + ); + RequestParam(request => request.Name, "The name of the playlist. Required, maximum 255 characters."); + RequestParam(request => request.Description, "The description of the playlist. Optional, maximum 2000 characters."); + + Response(200, "The updated playlist details are returned.", + example: new SuccessResponse(true, default) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx index a133070f..ff3cda79 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ar-SA.resx @@ -127,6 +127,9 @@ تشغيل - الإجراءات + الإجراءات + + + إضافة إلى قائمة التشغيل diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx index 825274d7..c743433f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.de-DE.resx @@ -129,4 +129,7 @@ Aktionen + + Zur Wiedergabeliste hinzufügen + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx index 415dbe8a..1c9fa57e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.en-US.resx @@ -129,4 +129,7 @@ Actions + + Add to playlist + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx index a870c71c..318fe196 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.es-ES.resx @@ -129,4 +129,7 @@ Acciones + + Añadir a la lista de reproducción + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx index 9a0c1dd5..6c3ca82e 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.fr-FR.resx @@ -129,4 +129,7 @@ Actions + + Ajouter à la liste de lecture + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx index 14f23a6c..6cb4db05 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.it-IT.resx @@ -129,4 +129,7 @@ Azioni + + Aggiungi alla playlist + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx index cc46497a..d42580a2 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ja-JP.resx @@ -127,6 +127,9 @@ 再生 - 操作 + 操作 + + + プレイリストに追加 \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx index 323d25af..f36b87c8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.resx @@ -129,4 +129,7 @@ Actions + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx index ab599e63..f151004b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.ro-RO.resx @@ -127,6 +127,9 @@ Redare - AcÈ›iuni + Acțiuni + + + Adaugă în listă de redare \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx index e97e6a6e..85ef450d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.uk-UA.resx @@ -127,6 +127,9 @@ Відтворити - Дії + Дії + + + Додати до списку відтворення diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx index 31dde401..9b6d6bac 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Home/Index.zh-CN.resx @@ -127,6 +127,9 @@ 播放 - 操作 + 操作 + + + 添加到播放列表 \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx index 48af1259..3bd47122 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ar-SA.resx @@ -1512,4 +1512,16 @@ تشغيل المقطع + + الإجراءات + + + إضافة إلى قائمة التشغيل + + + إضافة إلى قائمة الانتظار + + + تشغيل الكل من هنا + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx index deec8e3a..aff9b474 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.de-DE.resx @@ -1512,4 +1512,16 @@ Titel abspielen + + Aktionen + + + Zur Wiedergabeliste hinzufügen + + + Zur Warteschlange hinzufügen + + + Alles ab hier abspielen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx index fb3a061d..2382c00f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.en-US.resx @@ -703,7 +703,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -1030,7 +1030,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -1117,7 +1117,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1512,4 +1512,16 @@ Play track + + Actions + + + Add to playlist + + + Add to play queue + + + Play all from here + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx index a2a79c84..189dd913 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.es-ES.resx @@ -1512,4 +1512,16 @@ Reproducir la pista + + Acciones + + + Añadir a la lista de reproducción + + + Añadir a la cola de reproducción + + + Reproducir todo desde aquí + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx index 4b061200..777913bf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.fr-FR.resx @@ -1512,4 +1512,16 @@ Lire la piste + + Actions + + + Ajouter à la liste de lecture + + + Ajouter à la file d'attente + + + Lire tout à partir d'ici + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx index d0880c8b..b3d55ce8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.it-IT.resx @@ -1512,4 +1512,16 @@ Riproduci il brano + + Azioni + + + Aggiungi alla playlist + + + Aggiungi alla coda di riproduzione + + + Riproduci tutto da qui + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx index 09d32b4a..810da193 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ja-JP.resx @@ -1512,4 +1512,16 @@ トラックを再生 + + 操作 + + + プレイリストに追加 + + + 再生キューに追加 + + + ここからすべて再生 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx index fb3a061d..2382c00f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.resx @@ -703,7 +703,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -1030,7 +1030,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -1117,7 +1117,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1512,4 +1512,16 @@ Play track + + Actions + + + Add to playlist + + + Add to play queue + + + Play all from here + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx index d5b4450e..55fb6618 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.ro-RO.resx @@ -1512,4 +1512,16 @@ Redă piesa + + Acțiuni + + + Adaugă în listă de redare + + + Adaugă la coada de redare + + + Redă tot de aici + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx index d6047140..68684f8d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.uk-UA.resx @@ -1512,4 +1512,16 @@ Відтворити трек + + Дії + + + Додати до списку відтворення + + + Додати до черги відтворення + + + Відтворити все звідси + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx index 22ed5241..43685e57 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.zh-CN.resx @@ -1512,4 +1512,16 @@ 播放曲目 + + 操作 + + + 添加到播放列表 + + + 添加到播放队列 + + + 从这里开始播放全部 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx index 52e403e4..51c3d569 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ar-SA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -64,6 +64,9 @@ تشغيل - الإجراءات + الإجراءات + + + إضافة إلى قائمة التشغيل diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx index a9e22ebf..9629c2e8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.de-DE.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -66,4 +66,7 @@ Aktionen + + Zur Wiedergabeliste hinzufügen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx index 5bb671ad..70edc6b1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.en-US.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -66,4 +66,7 @@ Actions + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx index 09d9f795..ef56aa55 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.es-ES.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -66,4 +66,7 @@ Acciones + + Añadir a la lista de reproducción + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx index 86a4cea3..54a1c039 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.fr-FR.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -66,4 +66,7 @@ Actions + + Ajouter à la liste de lecture + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx index a3769c02..3a94a7da 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.it-IT.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -66,4 +66,7 @@ Azioni + + Aggiungi alla playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx index 0fa05bb3..e1f3718d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ja-JP.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -64,6 +64,9 @@ 再生 - 操作 + 操作 + + + プレイリストに追加 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx index 5bb671ad..70edc6b1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -66,4 +66,7 @@ Actions + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx index eb374db2..4860c230 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.ro-RO.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -64,6 +64,9 @@ Redare - AcÈ›iuni + Acțiuni + + + Adaugă în listă de redare diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx index cca619da..9ceafb1b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -64,6 +64,9 @@ Відтворити - Дії + Дії + + + Додати до списку відтворення diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx index 7358fdc9..18859dc1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.zh-CN.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -64,6 +64,9 @@ 播放 - 操作 + 操作 + + + 添加到播放列表 diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx index 1823197b..55834262 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ar-SA.resx @@ -1092,4 +1092,7 @@ تشغيل عشوائي + + إضافة إلى قائمة التشغيل + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx index 29afa2e5..8b0540ed 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.de-DE.resx @@ -1092,4 +1092,7 @@ Zufällige Wiedergabe + + Zur Wiedergabeliste hinzufügen + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx index 0162f675..9752bc4d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.en-US.resx @@ -445,7 +445,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -772,7 +772,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -859,7 +859,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1092,4 +1092,7 @@ Shuffle + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx index 0841e7e3..9ba90f4d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.es-ES.resx @@ -1092,4 +1092,7 @@ Aleatorio + + Añadir a la lista de reproducción + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx index d397e238..db7d04ec 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.fr-FR.resx @@ -1092,4 +1092,7 @@ Lecture aléatoire + + Ajouter à la liste de lecture + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx index 02f7ebb3..1e23fd35 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.it-IT.resx @@ -1092,4 +1092,7 @@ Riproduzione casuale + + Aggiungi alla playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx index 4078e895..53aea91d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ja-JP.resx @@ -1092,4 +1092,7 @@ シャッフル + + プレイリストに追加 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx index 0162f675..9752bc4d 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.resx @@ -445,7 +445,7 @@ Costa Rica - Côte d’Ivoire + Côte d’Ivoire Croatia @@ -772,7 +772,7 @@ San Marino - São Tomé & Príncipe + São Tomé & Príncipe Saudi Arabia @@ -859,7 +859,7 @@ Tunisia - Türkiye + Türkiye Turkmenistan @@ -1092,4 +1092,7 @@ Shuffle + + Add to playlist + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx index 66dd4b7f..f23f4ff7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.ro-RO.resx @@ -1092,4 +1092,7 @@ Aleatoriu + + Adaugă în listă de redare + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx index c7e9c341..edeb5536 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.uk-UA.resx @@ -1092,4 +1092,7 @@ Перемішати + + Додати до списку відтворення + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx index 5994d041..868949d8 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.zh-CN.resx @@ -1092,4 +1092,7 @@ 随机播放 + + 添加到播放列表 + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx index 5ee84d3a..9b2c7185 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.en-US.resx @@ -655,7 +655,7 @@ Switzerland - Côte d’Ivoire + Côte d’Ivoire Chile @@ -1048,7 +1048,7 @@ South Sudan - São Tomé & Príncipe + São Tomé & Príncipe El Salvador @@ -1084,7 +1084,7 @@ Tonga - Türkiye + Türkiye Trinidad & Tobago diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx index 5ee84d3a..9b2c7185 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/AudioLibrary/MusicLibrary/Tracks/Item.resx @@ -655,7 +655,7 @@ Switzerland - Côte d’Ivoire + Côte d’Ivoire Chile @@ -1048,7 +1048,7 @@ South Sudan - São Tomé & Príncipe + São Tomé & Príncipe El Salvador @@ -1084,7 +1084,7 @@ Tonga - Türkiye + Türkiye Trinidad & Tobago diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx new file mode 100644 index 00000000..9d9c41dd --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ar-SA.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + قوائم التشغيل + + + الاسم + + + الوصف + + + إنشاء + + + ليست لديك أي قوائم تشغيل بعد. + + + مقاطع + + + حذف + + + هل تريد حذف قائمة التشغيل هذه؟ لا يمكن التراجع عن هذا الإجراء. + + + تعذر حذف قائمة التشغيل. + + + تعذر إنشاء قائمة التشغيل. + + + تحتاج قائمة التشغيل إلى اسم. + + + عناصر + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx new file mode 100644 index 00000000..d4f25689 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.de-DE.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Wiedergabelisten + + + Name + + + Beschreibung + + + Erstellen + + + Du hast noch keine Wiedergabelisten. + + + Titel + + + Löschen + + + Diese Wiedergabeliste löschen? Das kann nicht rückgängig gemacht werden. + + + Die Wiedergabeliste konnte nicht gelöscht werden. + + + Die Wiedergabeliste konnte nicht erstellt werden. + + + Eine Wiedergabeliste braucht einen Namen. + + + Einträge + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx new file mode 100644 index 00000000..b9fda170 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.en-US.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Playlists + + + Name + + + Description + + + Create + + + You have no playlists yet. + + + tracks + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + The playlist could not be created. + + + A playlist needs a name. + + + items + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx new file mode 100644 index 00000000..2451e8c3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.es-ES.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Listas de reproducción + + + Nombre + + + Descripción + + + Crear + + + Todavía no tienes listas de reproducción. + + + pistas + + + Eliminar + + + ¿Eliminar esta lista de reproducción? No se puede deshacer. + + + No se pudo eliminar la lista de reproducción. + + + No se pudo crear la lista de reproducción. + + + Una lista de reproducción necesita un nombre. + + + elementos + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx new file mode 100644 index 00000000..826e8342 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.fr-FR.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Listes de lecture + + + Nom + + + Description + + + Créer + + + Vous n'avez encore aucune liste de lecture. + + + pistes + + + Supprimer + + + Supprimer cette liste de lecture ? Cette action est irréversible. + + + La liste de lecture n'a pas pu être supprimée. + + + La liste de lecture n'a pas pu être créée. + + + Une liste de lecture doit avoir un nom. + + + éléments + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx new file mode 100644 index 00000000..a019457b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.it-IT.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Playlist + + + Nome + + + Descrizione + + + Crea + + + Non hai ancora playlist. + + + brani + + + Elimina + + + Eliminare questa playlist? L'operazione non può essere annullata. + + + Non è stato possibile eliminare la playlist. + + + Non è stato possibile creare la playlist. + + + Una playlist deve avere un nome. + + + elementi + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx new file mode 100644 index 00000000..ed9196d1 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ja-JP.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + プレイリスト + + + 名前 + + + 説明 + + + 作成 + + + プレイリストはまだありません。 + + + 曲 + + + 削除 + + + このプレイリストを削除しますか?この操作は元に戻せません。 + + + プレイリストを削除できませんでした。 + + + プレイリストを作成できませんでした。 + + + プレイリストには名前が必要です。 + + + 件 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx new file mode 100644 index 00000000..b9fda170 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Playlists + + + Name + + + Description + + + Create + + + You have no playlists yet. + + + tracks + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + The playlist could not be created. + + + A playlist needs a name. + + + items + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx new file mode 100644 index 00000000..21fa9387 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.ro-RO.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Liste de redare + + + Nume + + + Descriere + + + Creează + + + Nu ai încă liste de redare. + + + piese + + + Șterge + + + Ștergi această listă de redare? Această acțiune nu poate fi anulată. + + + Lista de redare nu a putut fi ștearsă. + + + Lista de redare nu a putut fi creată. + + + O listă de redare are nevoie de un nume. + + + elemente + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx new file mode 100644 index 00000000..d4003617 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.uk-UA.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Списки відтворення + + + Назва + + + Опис + + + Створити + + + У вас ще немає списків відтворення. + + + треків + + + Видалити + + + Видалити цей список відтворення? Цю дію неможливо скасувати. + + + Не вдалося видалити список відтворення. + + + Не вдалося створити список відтворення. + + + Список відтворення повинен мати назву. + + + елементів + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx new file mode 100644 index 00000000..a9792e57 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Index.zh-CN.resx @@ -0,0 +1,51 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 播放列表 + + + 名称 + + + 描述 + + + 创建 + + + 你还没有播放列表。 + + + 首曲目 + + + 删除 + + + 删除此播放列表?此操作无法撤销。 + + + 无法删除播放列表。 + + + 无法创建播放列表。 + + + 播放列表需要名称。 + + + 项 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx new file mode 100644 index 00000000..fa3b2c2b --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ar-SA.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + تشغيل + + + تشغيل قائمة التشغيل + + + حفظ + + + تم حفظ قائمة التشغيل. + + + تعذر حفظ قائمة التشغيل. + + + حذف + + + هل تريد حذف قائمة التشغيل هذه؟ لا يمكن التراجع عن هذا الإجراء. + + + تعذر حذف قائمة التشغيل. + + + العودة إلى قوائم التشغيل + + + المقاطع + + + لا تحتوي قائمة التشغيل هذه على مقاطع بعد. + + + إضافة مقطع + + + المكتبة + + + الفنان + + + الألبوم + + + المقطع + + + إضافة + + + تعذر إضافة المقطع. + + + اختر مكتبة + + + اختر فنانًا + + + اختر ألبومًا + + + اختر مقطعًا + + + نقل لأعلى + + + نقل لأسفل + + + إزالة + + + هل تريد إزالة هذا المقطع من قائمة التشغيل؟ + + + تعذرت إزالة المقطع. + + + تعذر إعادة ترتيب قائمة التشغيل. + + + مقطع غير متاح + + + تحتاج قائمة التشغيل إلى اسم. + + + لا تحتوي قائمة التشغيل هذه على مقاطع قابلة للتشغيل. + + + مشغل الصوت غير متاح. + + + تفاصيل قائمة التشغيل + + + الاسم + + + الوصف + + + ليست لديك مكتبات موسيقى بعد. + + + جارٍ التحميل... + + + اسحب لإعادة الترتيب + + + إنشاء قائمة تشغيل + + + إلغاء + + + تحميل المزيد + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx new file mode 100644 index 00000000..f4ff23be --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.de-DE.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Abspielen + + + Wiedergabeliste abspielen + + + Speichern + + + Die Wiedergabeliste wurde gespeichert. + + + Die Wiedergabeliste konnte nicht gespeichert werden. + + + Löschen + + + Diese Wiedergabeliste löschen? Das kann nicht rückgängig gemacht werden. + + + Die Wiedergabeliste konnte nicht gelöscht werden. + + + Zurück zu den Wiedergabelisten + + + Titel + + + Diese Wiedergabeliste hat noch keine Titel. + + + Titel hinzufügen + + + Bibliothek + + + Künstler + + + Album + + + Titel + + + Hinzufügen + + + Der Titel konnte nicht hinzugefügt werden. + + + Bibliothek auswählen + + + Künstler auswählen + + + Album auswählen + + + Titel auswählen + + + Nach oben + + + Nach unten + + + Entfernen + + + Diesen Titel aus der Wiedergabeliste entfernen? + + + Der Titel konnte nicht entfernt werden. + + + Die Wiedergabeliste konnte nicht neu sortiert werden. + + + Nicht verfügbarer Titel + + + Eine Wiedergabeliste braucht einen Namen. + + + Diese Wiedergabeliste enthält keine abspielbaren Titel. + + + Der Audioplayer ist nicht verfügbar. + + + Details der Wiedergabeliste + + + Name + + + Beschreibung + + + Du hast noch keine Musikbibliotheken. + + + Wird geladen... + + + Ziehen zum Sortieren + + + Wiedergabeliste erstellen + + + Abbrechen + + + Mehr laden + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx new file mode 100644 index 00000000..34541b79 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.en-US.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Play + + + Play playlist + + + Save + + + The playlist was saved. + + + The playlist could not be saved. + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + Back to playlists + + + Tracks + + + This playlist has no tracks yet. + + + Add a track + + + Library + + + Artist + + + Album + + + Track + + + Add + + + The track could not be added. + + + Select a library + + + Select an artist + + + Select an album + + + Select a track + + + Move up + + + Move down + + + Remove + + + Remove this track from the playlist? + + + The track could not be removed. + + + The playlist could not be reordered. + + + Unavailable track + + + A playlist needs a name. + + + There are no playable tracks in this playlist. + + + The audio player is not available. + + + Playlist details + + + Name + + + Description + + + You have no music libraries yet. + + + Loading... + + + Drag to reorder + + + Create playlist + + + Cancel + + + Load more + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx new file mode 100644 index 00000000..786a8423 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.es-ES.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Reproducir + + + Reproducir lista + + + Guardar + + + La lista de reproducción se guardó. + + + No se pudo guardar la lista de reproducción. + + + Eliminar + + + ¿Eliminar esta lista de reproducción? No se puede deshacer. + + + No se pudo eliminar la lista de reproducción. + + + Volver a las listas + + + Pistas + + + Esta lista de reproducción todavía no tiene pistas. + + + Añadir una pista + + + Biblioteca + + + Artista + + + Álbum + + + Pista + + + Añadir + + + No se pudo añadir la pista. + + + Selecciona una biblioteca + + + Selecciona un artista + + + Selecciona un álbum + + + Selecciona una pista + + + Subir + + + Bajar + + + Quitar + + + ¿Quitar esta pista de la lista de reproducción? + + + No se pudo quitar la pista. + + + No se pudo reordenar la lista de reproducción. + + + Pista no disponible + + + Una lista de reproducción necesita un nombre. + + + Esta lista de reproducción no contiene pistas reproducibles. + + + El reproductor de audio no está disponible. + + + Detalles de la lista + + + Nombre + + + Descripción + + + Todavía no tienes bibliotecas de música. + + + Cargando... + + + Arrastra para reordenar + + + Crear lista de reproducción + + + Cancelar + + + Cargar más + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx new file mode 100644 index 00000000..a802ac12 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.fr-FR.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Lire + + + Lire la liste de lecture + + + Enregistrer + + + La liste de lecture a été enregistrée. + + + La liste de lecture n'a pas pu être enregistrée. + + + Supprimer + + + Supprimer cette liste de lecture ? Cette action est irréversible. + + + La liste de lecture n'a pas pu être supprimée. + + + Retour aux listes de lecture + + + Pistes + + + Cette liste de lecture n'a encore aucune piste. + + + Ajouter une piste + + + Bibliothèque + + + Artiste + + + Album + + + Piste + + + Ajouter + + + La piste n'a pas pu être ajoutée. + + + Choisir une bibliothèque + + + Choisir un artiste + + + Choisir un album + + + Choisir une piste + + + Monter + + + Descendre + + + Retirer + + + Retirer cette piste de la liste de lecture ? + + + La piste n'a pas pu être retirée. + + + La liste de lecture n'a pas pu être réorganisée. + + + Piste indisponible + + + Une liste de lecture doit avoir un nom. + + + Cette liste de lecture ne contient aucune piste lisible. + + + Le lecteur audio n'est pas disponible. + + + Détails de la liste de lecture + + + Nom + + + Description + + + Vous n'avez encore aucune bibliothèque musicale. + + + Chargement... + + + Faire glisser pour réorganiser + + + Créer une liste de lecture + + + Annuler + + + Charger plus + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx new file mode 100644 index 00000000..aa542530 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.it-IT.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Riproduci + + + Riproduci playlist + + + Salva + + + La playlist è stata salvata. + + + Non è stato possibile salvare la playlist. + + + Elimina + + + Eliminare questa playlist? L'operazione non può essere annullata. + + + Non è stato possibile eliminare la playlist. + + + Torna alle playlist + + + Brani + + + Questa playlist non contiene ancora brani. + + + Aggiungi un brano + + + Libreria + + + Artista + + + Album + + + Brano + + + Aggiungi + + + Non è stato possibile aggiungere il brano. + + + Seleziona una libreria + + + Seleziona un artista + + + Seleziona un album + + + Seleziona un brano + + + Sposta su + + + Sposta giù + + + Rimuovi + + + Rimuovere questo brano dalla playlist? + + + Non è stato possibile rimuovere il brano. + + + Non è stato possibile riordinare la playlist. + + + Brano non disponibile + + + Una playlist deve avere un nome. + + + Questa playlist non contiene brani riproducibili. + + + Il lettore audio non è disponibile. + + + Dettagli della playlist + + + Nome + + + Descrizione + + + Non hai ancora librerie musicali. + + + Caricamento... + + + Trascina per riordinare + + + Crea playlist + + + Annulla + + + Carica altro + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx new file mode 100644 index 00000000..b41745ef --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ja-JP.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 再生 + + + プレイリストを再生 + + + 保存 + + + プレイリストを保存しました。 + + + プレイリストを保存できませんでした。 + + + 削除 + + + このプレイリストを削除しますか?この操作は元に戻せません。 + + + プレイリストを削除できませんでした。 + + + プレイリストに戻る + + + 曲 + + + このプレイリストにはまだ曲がありません。 + + + 曲を追加 + + + ライブラリ + + + アーティスト + + + アルバム + + + 曲 + + + 追加 + + + 曲を追加できませんでした。 + + + ライブラリを選択 + + + アーティストを選択 + + + アルバムを選択 + + + 曲を選択 + + + 上へ + + + 下へ + + + 削除 + + + この曲をプレイリストから削除しますか? + + + 曲を削除できませんでした。 + + + プレイリストを並べ替えできませんでした。 + + + 利用できない曲 + + + プレイリストには名前が必要です。 + + + このプレイリストには再生できる曲がありません。 + + + オーディオプレーヤーを利用できません。 + + + プレイリストの詳細 + + + 名前 + + + 説明 + + + 音楽ライブラリはまだありません。 + + + 読み込み中... + + + ドラッグして並べ替え + + + プレイリストを作成 + + + キャンセル + + + さらに読み込む + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx new file mode 100644 index 00000000..34541b79 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Play + + + Play playlist + + + Save + + + The playlist was saved. + + + The playlist could not be saved. + + + Delete + + + Delete this playlist? This cannot be undone. + + + The playlist could not be deleted. + + + Back to playlists + + + Tracks + + + This playlist has no tracks yet. + + + Add a track + + + Library + + + Artist + + + Album + + + Track + + + Add + + + The track could not be added. + + + Select a library + + + Select an artist + + + Select an album + + + Select a track + + + Move up + + + Move down + + + Remove + + + Remove this track from the playlist? + + + The track could not be removed. + + + The playlist could not be reordered. + + + Unavailable track + + + A playlist needs a name. + + + There are no playable tracks in this playlist. + + + The audio player is not available. + + + Playlist details + + + Name + + + Description + + + You have no music libraries yet. + + + Loading... + + + Drag to reorder + + + Create playlist + + + Cancel + + + Load more + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx new file mode 100644 index 00000000..1ccaf967 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.ro-RO.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Redă + + + Redă lista de redare + + + Salvează + + + Lista de redare a fost salvată. + + + Lista de redare nu a putut fi salvată. + + + Șterge + + + Ștergi această listă de redare? Această acțiune nu poate fi anulată. + + + Lista de redare nu a putut fi ștearsă. + + + Înapoi la liste de redare + + + Piese + + + Această listă de redare nu are încă piese. + + + Adaugă o piesă + + + Bibliotecă + + + Artist + + + Album + + + Piesă + + + Adaugă + + + Piesa nu a putut fi adăugată. + + + Selectează o bibliotecă + + + Selectează un artist + + + Selectează un album + + + Selectează o piesă + + + Mută în sus + + + Mută în jos + + + Elimină + + + Elimini această piesă din lista de redare? + + + Piesa nu a putut fi eliminată. + + + Lista de redare nu a putut fi reordonată. + + + Piesă indisponibilă + + + O listă de redare are nevoie de un nume. + + + Această listă de redare nu conține piese care pot fi redate. + + + Playerul audio nu este disponibil. + + + Detalii listă de redare + + + Nume + + + Descriere + + + Nu ai încă biblioteci muzicale. + + + Se încarcă... + + + Trage pentru a reordona + + + Creează listă de redare + + + Anulează + + + Încarcă mai multe + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx new file mode 100644 index 00000000..747a3756 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.uk-UA.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Відтворити + + + Відтворити список + + + Зберегти + + + Список відтворення збережено. + + + Не вдалося зберегти список відтворення. + + + Видалити + + + Видалити цей список відтворення? Цю дію неможливо скасувати. + + + Не вдалося видалити список відтворення. + + + Назад до списків відтворення + + + Треки + + + У цьому списку відтворення ще немає треків. + + + Додати трек + + + Бібліотека + + + Виконавець + + + Альбом + + + Трек + + + Додати + + + Не вдалося додати трек. + + + Виберіть бібліотеку + + + Виберіть виконавця + + + Виберіть альбом + + + Виберіть трек + + + Вгору + + + Вниз + + + Прибрати + + + Прибрати цей трек зі списку відтворення? + + + Не вдалося прибрати трек. + + + Не вдалося змінити порядок списку відтворення. + + + Недоступний трек + + + Список відтворення повинен мати назву. + + + У цьому списку відтворення немає треків для відтворення. + + + Аудіоплеєр недоступний. + + + Деталі списку відтворення + + + Назва + + + Опис + + + У вас ще немає музичних бібліотек. + + + Завантаження... + + + Перетягніть, щоб змінити порядок + + + Створити список відтворення + + + Скасувати + + + Завантажити більше + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx new file mode 100644 index 00000000..d4e2c3e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Playlists/Item.zh-CN.resx @@ -0,0 +1,138 @@ + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 播放 + + + 播放列表 + + + 保存 + + + 播放列表已保存。 + + + 无法保存播放列表。 + + + 删除 + + + 删除此播放列表?此操作无法撤销。 + + + 无法删除播放列表。 + + + 返回播放列表 + + + 曲目 + + + 此播放列表还没有曲目。 + + + 添加曲目 + + + 库 + + + 艺术家 + + + 专辑 + + + 曲目 + + + 添加 + + + 无法添加曲目。 + + + 选择库 + + + 选择艺术家 + + + 选择专辑 + + + 选择曲目 + + + 上移 + + + 下移 + + + 移除 + + + 从此播放列表中移除此曲目? + + + 无法移除曲目。 + + + 无法重新排序播放列表。 + + + 不可用的曲目 + + + 播放列表需要名称。 + + + 此播放列表中没有可播放的曲目。 + + + 音频播放器不可用。 + + + 播放列表详情 + + + 名称 + + + 描述 + + + 你还没有音乐库。 + + + 加载中... + + + 拖动以重新排序 + + + 创建播放列表 + + + 取消 + + + 加载更多 + + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx index a722b98c..6796047c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ar-SA.resx @@ -222,4 +222,37 @@ أعمال فنية للألبوم + + إضافة قائمة الانتظار إلى قائمة تشغيل + + + تعذرت إضافة قائمة الانتظار إلى قائمة التشغيل. + + + اختر قائمة تشغيل + + + إضافة + + + تمت إضافة قائمة الانتظار إلى قائمة التشغيل. + + + ليست لديك قوائم تشغيل بعد. + + + إضافة إلى قائمة التشغيل + + + إنشاء قائمة تشغيل + + + تمت إضافة المقاطع إلى قائمة التشغيل. + + + تعذر إضافة المقاطع إلى قائمة التشغيل. + + + لا توجد مقاطع لإضافتها. + diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx index 5fddf232..0e2fb338 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.de-DE.resx @@ -222,4 +222,37 @@ Albumcover + + Warteschlange zu Wiedergabeliste hinzufügen + + + Die Warteschlange konnte nicht zur Wiedergabeliste hinzugefügt werden. + + + Wiedergabeliste auswählen + + + Hinzufügen + + + Die Warteschlange wurde der Wiedergabeliste hinzugefügt. + + + Du hast noch keine Wiedergabelisten. + + + Zur Wiedergabeliste hinzufügen + + + Wiedergabeliste erstellen + + + Die Titel wurden zur Wiedergabeliste hinzugefügt. + + + Die Titel konnten nicht zur Wiedergabeliste hinzugefügt werden. + + + Es gibt keine Titel zum Hinzufügen. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx index dc6bfb30..adfbf502 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.en-US.resx @@ -222,4 +222,37 @@ Album artwork + + Add queue to playlist + + + The queue could not be added to the playlist. + + + Select a playlist + + + Add + + + The queue was added to the playlist. + + + You have no playlists yet. + + + Add to playlist + + + Create playlist + + + The tracks were added to the playlist. + + + The tracks could not be added to the playlist. + + + There are no tracks to add. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx index 5a566876..5cc273c3 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.es-ES.resx @@ -222,4 +222,37 @@ Ilustraciones del álbum + + Añadir la cola a una lista de reproducción + + + No se pudo añadir la cola a la lista de reproducción. + + + Selecciona una lista de reproducción + + + Añadir + + + La cola se añadió a la lista de reproducción. + + + Todavía no tienes listas de reproducción. + + + Añadir a la lista de reproducción + + + Crear lista de reproducción + + + Las pistas se añadieron a la lista de reproducción. + + + No se pudieron añadir las pistas a la lista de reproducción. + + + No hay pistas para añadir. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx index b8949e55..1b80c9b9 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.fr-FR.resx @@ -222,4 +222,37 @@ Illustrations de l'album + + Ajouter la file d'attente à une liste de lecture + + + La file d'attente n'a pas pu être ajoutée à la liste de lecture. + + + Choisir une liste de lecture + + + Ajouter + + + La file d'attente a été ajoutée à la liste de lecture. + + + Vous n'avez encore aucune liste de lecture. + + + Ajouter à la liste de lecture + + + Créer une liste de lecture + + + Les pistes ont été ajoutées à la liste de lecture. + + + Les pistes n'ont pas pu être ajoutées à la liste de lecture. + + + Il n'y a aucune piste à ajouter. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx index d2df229a..a4a82f09 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.it-IT.resx @@ -222,4 +222,37 @@ Illustrazioni dell'album + + Aggiungi la coda a una playlist + + + Non è stato possibile aggiungere la coda alla playlist. + + + Seleziona una playlist + + + Aggiungi + + + La coda è stata aggiunta alla playlist. + + + Non hai ancora playlist. + + + Aggiungi alla playlist + + + Crea playlist + + + Le tracce sono state aggiunte alla playlist. + + + Non è stato possibile aggiungere le tracce alla playlist. + + + Non ci sono tracce da aggiungere. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx index df5802a7..53c23663 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ja-JP.resx @@ -222,4 +222,37 @@ アルバムアートワーク + + キューをプレイリストに追加 + + + キューをプレイリストに追加できませんでした。 + + + プレイリストを選択 + + + 追加 + + + キューをプレイリストに追加しました。 + + + プレイリストはまだありません。 + + + プレイリストに追加 + + + プレイリストを作成 + + + トラックをプレイリストに追加しました。 + + + トラックをプレイリストに追加できませんでした。 + + + 追加するトラックがありません。 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx index dc6bfb30..adfbf502 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.resx @@ -222,4 +222,37 @@ Album artwork + + Add queue to playlist + + + The queue could not be added to the playlist. + + + Select a playlist + + + Add + + + The queue was added to the playlist. + + + You have no playlists yet. + + + Add to playlist + + + Create playlist + + + The tracks were added to the playlist. + + + The tracks could not be added to the playlist. + + + There are no tracks to add. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx index eed34890..225cccd7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.ro-RO.resx @@ -222,4 +222,37 @@ Ilustrații album + + Adaugă coada la o listă de redare + + + Coada nu a putut fi adăugată în lista de redare. + + + Selectează o listă de redare + + + Adaugă + + + Coada a fost adăugată în lista de redare. + + + Nu ai încă liste de redare. + + + Adaugă în listă de redare + + + Creează listă de redare + + + Piesele au fost adăugate în lista de redare. + + + Piesele nu au putut fi adăugate în lista de redare. + + + Nu există piese de adăugat. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx index 67f13815..32e66a50 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.uk-UA.resx @@ -222,4 +222,37 @@ Обкладинки альбому + + Додати чергу до списку відтворення + + + Не вдалося додати чергу до списку відтворення. + + + Виберіть список відтворення + + + Додати + + + Чергу додано до списку відтворення. + + + У вас ще немає списків відтворення. + + + Додати до списку відтворення + + + Створити список відтворення + + + Треки додано до списку відтворення. + + + Не вдалося додати треки до списку відтворення. + + + Немає треків для додавання. + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx index caddd33e..95f8d2e7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_Layout.zh-CN.resx @@ -222,4 +222,37 @@ 专辑插图 + + 将队列添加到播放列表 + + + 无法将队列添加到播放列表。 + + + 选择播放列表 + + + 添加 + + + 队列已添加到播放列表。 + + + 你还没有播放列表。 + + + 添加到播放列表 + + + 创建播放列表 + + + 曲目已添加到播放列表。 + + + 无法将曲目添加到播放列表。 + + + 没有可添加的曲目。 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx index 021c346f..bb2a1368 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx @@ -219,4 +219,7 @@ المهام المجدولة + + قوائم التشغيل + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx index 659af2bb..9c6a08e7 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx @@ -219,4 +219,7 @@ Geplante Aufgaben + + Wiedergabelisten + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx index ec0f3849..7f886cd6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx @@ -219,4 +219,7 @@ Scheduled jobs + + Playlists + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx index 0b9eadbd..236c905b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx @@ -219,4 +219,7 @@ Tareas programadas + + Listas de reproducción + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx index 584fc220..82fc9d3f 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx @@ -219,4 +219,7 @@ Tâches planifiées + + Listes de lecture + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx index 01f50714..d77a860c 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx @@ -219,4 +219,7 @@ Attività pianificate + + Playlist + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx index e1fed3a1..1d7aab75 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx @@ -219,4 +219,7 @@ スケジュール済みジョブ + + プレイリスト + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx index ec0f3849..7f886cd6 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx @@ -219,4 +219,7 @@ Scheduled jobs + + Playlists + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx index 3ec9eeaf..26115285 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx @@ -219,4 +219,7 @@ Sarcini programate + + Liste de redare + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx index 7583f730..926a6e54 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx @@ -219,4 +219,7 @@ Заплановані завдання + + Списки відтворення + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx index 6cd03b6d..359add67 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx @@ -219,4 +219,7 @@ 计划任务 + + 播放列表 + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs index 0bc98252..49dedda4 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeAudioPlayerBuilder.cs @@ -50,7 +50,14 @@ public sealed class ThemeAudioPlayerBuilder ["repeatAll"] = Localize("AudioPlayerRepeatAll"), ["repeatOne"] = Localize("AudioPlayerRepeatOne"), ["queue"] = Localize("AudioPlayerQueue"), - ["albumArtwork"] = Localize("AudioPlayerAlbumArtwork") + ["albumArtwork"] = Localize("AudioPlayerAlbumArtwork"), + ["addQueueToPlaylist"] = Localize("AudioPlayerAddQueueToPlaylist"), + ["addToPlaylist"] = Localize("PlaylistAddToPlaylist"), + ["selectPlaylist"] = Localize("AudioPlayerSelectPlaylist"), + ["noPlaylists"] = Localize("AudioPlayerNoPlaylists"), + ["add"] = Localize("AudioPlayerAdd"), + ["playlistQueueAdded"] = Localize("AudioPlayerPlaylistQueueAdded"), + ["playlistQueueAddFailed"] = Localize("AudioPlayerPlaylistQueueAddFailed") }; return new ThemeAudioPlayerDto( diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs index 63cfb3ce..52e1bd95 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs @@ -163,6 +163,7 @@ public sealed class ThemeNavBuilder items.Add(new ThemeNavEntryDto(Localize("Audio"), Url: null, CssClass: null, [ new ThemeNavEntryDto(Localize("Music"), $"{librariesCatalogUrl}?category=music", "nav-link", []), + new ThemeNavEntryDto(Localize("Playlists"), _urlService.GetAbsoluteUrl(WebRoutes.Playlists.INDEX), "nav-link", []), new ThemeNavEntryDto(Localize("Interviews"), "library/audio/interviews", "nav-link", []) ])); items.Add(new ThemeNavEntryDto(Localize("Video"), Url: null, CssClass: null, diff --git a/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml index c219bd18..32c73678 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Home/Index.cshtml @@ -62,7 +62,8 @@ const jsLocalizedStrings = { actions: @Json.Serialize(_localizer["Actions"].Value), play: @Json.Serialize(_localizer["Play"].Value), - shuffle: @Json.Serialize(_localizer["Shuffle"].Value) + shuffle: @Json.Serialize(_localizer["Shuffle"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value) }; // Closes the actions menus of all the music library cards. @@ -157,6 +158,20 @@ shuffleAction.dataset.libraryId = library.id; menu.appendChild(shuffleAction); + const addToPlaylistAction = document.createElement('a'); + addToPlaylistAction.setAttribute('role', 'menuitem'); + addToPlaylistAction.href = '#'; + addToPlaylistAction.className = 'card-action-add-to-playlist'; + addToPlaylistAction.textContent = jsLocalizedStrings.addToPlaylist; + addToPlaylistAction.addEventListener('click', async event => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeCardMenus(); + if (window.LuminaPlaylists) + await window.LuminaPlaylists.showAddScopeDialogAsync({ libraryId: library.id, title: library.title || '', addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, returnFocus: trigger }); + }); + menu.appendChild(addToPlaylistAction); + menu.addEventListener('click', event => { // The global audio player delegation handles the play and shuffle actions; the menu only closes here. if (event.target.closest('.card-action-play, .card-action-shuffle')) diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml index afa06ed2..181a7326 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Albums/Item.cshtml @@ -133,10 +133,11 @@
- + +
@@ -658,6 +659,10 @@ coverSaved: @Json.Serialize(_localizer["CoverSaved"].Value), coverUploadFailed: @Json.Serialize(_localizer["CoverUploadFailed"].Value), playTrack: @Json.Serialize(_localizer["PlayTrack"].Value), + actions: @Json.Serialize(_localizer["Actions"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value), + addToPlayQueue: @Json.Serialize(_localizer["AddToPlayQueue"].Value), + playAllFromHere: @Json.Serialize(_localizer["PlayAllFromHere"].Value), remove: @Json.Serialize(_localizer["Remove"].Value) }; @@ -668,6 +673,10 @@ // The cover path the play affordances hand to the player, kept in step with the artwork the page currently displays. let currentCoverPath = normalizeCoverPath(@Json.Serialize(playCoverPath ?? string.Empty)); + // The ordered tracks of the album, kept for the "play all from here" action of the track menu. + let albumTracks = []; + // The track actions menu that is currently open, so the page opens one menu at a time and closes it on dismissal. + let openTrackActionsMenu = null; // Writes the cover of a play descriptor onto a trigger, dropping the attribute when the context has no artwork. function applyDescriptorCover(trigger, coverPath) { @@ -954,6 +963,7 @@ return; tracksBody.innerHTML = ''; const tracks = response.data; + albumTracks = tracks; noTracksMessage.classList.toggle('hidden', tracks.length !== 0); // Only a successful empty list disables the play album trigger. The player can still build the queue itself when // the track list could not be loaded. @@ -966,7 +976,7 @@ function createTrackPlayButton(track) { const button = document.createElement('button'); button.type = 'button'; - button.className = 'confirm-button'; + button.className = 'confirm-button track-play-button'; button.setAttribute('data-audio-player-play', ''); button.dataset.libraryId = libraryId; button.dataset.trackId = track.id; @@ -984,12 +994,14 @@ return button; } - // Creates a row of the tracks table, with the play trigger, the number, the name of the track linking to its own page and the duration. + // Creates a row of the tracks table, with the play trigger, the number, the name of the track linking to its own page, + // the duration and the actions menu of the track. function createTrackRow(track) { const row = document.createElement('tr'); row.className = 'track-row'; const playCell = document.createElement('td'); + playCell.className = 'track-play-cell'; playCell.appendChild(createTrackPlayButton(track)); const numberCell = document.createElement('td'); @@ -1009,9 +1021,170 @@ row.appendChild(numberCell); row.appendChild(nameCell); row.appendChild(durationCell); + row.appendChild(createTrackActionsCell(track)); return row; } + // Gets the singleton audio player, or null when the layout did not render it. + function getAudioPlayer() { + return window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance + ? window.LuminaAudioPlayer.instance + : null; + } + + // Builds the play descriptor of a track of this album, with the cover the page currently displays. + function buildTrackDescriptor(track) { + return { + libraryId: libraryId, + trackId: track.id, + albumId: albumId, + artistId: artistId, + title: track.title || '', + albumTitle: albumTitle, + durationInSeconds: Number(track.durationInSeconds) || 0, + coverArtPath: currentCoverPath + }; + } + + // Closes the open track actions menu, optionally returning the focus to its trigger. + function closeTrackActionsMenu(shouldRestoreFocus) { + if (!openTrackActionsMenu) + return; + const menu = openTrackActionsMenu.menu; + const trigger = openTrackActionsMenu.trigger; + openTrackActionsMenu = null; + menu.remove(); + trigger.setAttribute('aria-expanded', 'false'); + if (shouldRestoreFocus && trigger.isConnected) + trigger.focus(); + } + + // Places the track actions menu next to its trigger, right aligned and below it when there is room. + function positionTrackActionsMenu(menu, trigger) { + const margin = 4; + const triggerRect = trigger.getBoundingClientRect(); + const width = menu.offsetWidth; + const height = menu.offsetHeight; + const left = Math.min(Math.max(margin, triggerRect.right - width), Math.max(margin, window.innerWidth - width - margin)); + const below = triggerRect.bottom + margin; + const top = below + height <= window.innerHeight - margin + ? below + : Math.max(margin, triggerRect.top - height - margin); + menu.style.left = `${left}px`; + menu.style.top = `${top}px`; + } + + // Creates one entry of the track actions menu, using the same menu item markup as the card actions menus. + function createTrackMenuAction(label, className, handler) { + const link = document.createElement('a'); + link.href = '#'; + link.className = className; + link.setAttribute('role', 'menuitem'); + link.textContent = label; + link.addEventListener('click', event => { + event.preventDefault(); + event.stopPropagation(); + closeTrackActionsMenu(false); + handler(); + }); + return link; + } + + // Opens the actions menu of a track, or closes it when the same trigger is clicked again. + function openTrackActionsMenuFor(trigger, track) { + const wasOpen = openTrackActionsMenu && openTrackActionsMenu.trigger === trigger; + closeTrackActionsMenu(false); + if (wasOpen) + return; + const menu = document.createElement('nav'); + menu.className = 'card-actions-menu'; + menu.setAttribute('role', 'menu'); + menu.appendChild(createTrackMenuAction(jsLocalizedStrings.addToPlaylist, 'card-action-add-to-playlist', () => addTrackToPlaylist(track, trigger))); + menu.appendChild(createTrackMenuAction(jsLocalizedStrings.addToPlayQueue, 'card-action-add-to-queue', () => addTrackToQueueAsync(track))); + menu.appendChild(createTrackMenuAction(jsLocalizedStrings.playAllFromHere, 'card-action-play-all-from-here', () => playAllFromHereAsync(track))); + document.body.appendChild(menu); + menu.classList.add('open'); + positionTrackActionsMenu(menu, trigger); + trigger.setAttribute('aria-expanded', 'true'); + openTrackActionsMenu = { trigger, menu }; + const firstAction = menu.querySelector('a[role="menuitem"]'); + if (firstAction) + firstAction.focus(); + } + + // Creates the actions cell of a track row, using the same trigger and dots as the card actions menus. + function createTrackActionsCell(track) { + const cell = document.createElement('td'); + cell.className = 'track-actions-cell'; + const trigger = document.createElement('button'); + trigger.type = 'button'; + trigger.className = 'card-actions-trigger track-actions-trigger'; + trigger.setAttribute('aria-haspopup', 'menu'); + trigger.setAttribute('aria-expanded', 'false'); + trigger.setAttribute('aria-label', jsLocalizedStrings.actions); + trigger.title = jsLocalizedStrings.actions; + trigger.addEventListener('click', event => { + event.preventDefault(); + event.stopPropagation(); + openTrackActionsMenuFor(trigger, track); + }); + cell.appendChild(trigger); + return cell; + } + + // Closes the track actions menu when the user clicks elsewhere, presses Escape, scrolls or resizes the window. + function handleTrackActionsMenuDismiss(event) { + if (!openTrackActionsMenu) + return; + if (event.type === 'keydown') { + if (event.key === 'Escape') { + event.preventDefault(); + closeTrackActionsMenu(true); + } + return; + } + if (event.type === 'click' && event.target.closest('.card-actions-menu, .track-actions-trigger')) + return; + closeTrackActionsMenu(false); + } + + // Appends one track to the play queue, or starts it when the queue is empty. + async function addTrackToQueueAsync(track) { + const player = getAudioPlayer(); + if (!player || typeof player.appendToQueueAsync !== 'function') + return; + await player.appendToQueueAsync(buildTrackDescriptor(track)); + } + + // Starts a new queue with the clicked track and every track that follows it in the album track list. + async function playAllFromHereAsync(track) { + const player = getAudioPlayer(); + if (!player) + return; + const index = albumTracks.findIndex(candidate => candidate.id === track.id); + if (index < 0) + return; + const descriptors = albumTracks.slice(index).map(buildTrackDescriptor); + if (descriptors.length === 0) + return; + await player.playAsync({ ...descriptors[0], queue: descriptors }); + } + + // Opens the shared add-to-playlist dialog for this single track. + function addTrackToPlaylist(track, trigger) { + if (!window.LuminaPlaylists || typeof window.LuminaPlaylists.showAddScopeDialogAsync !== 'function') + return; + window.LuminaPlaylists.showAddScopeDialogAsync({ + libraryId: libraryId, + artistId: artistId, + albumId: albumId, + trackId: track.id, + title: track.title || '', + addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, + returnFocus: trigger + }); + } + // Sends the edited album data to the server. async function handleSaveAsync() { const result = await callApiPutAsync(`${saveUrl}?libraryId=${encodeURIComponent(libraryId)}`, buildPayload()); @@ -1160,6 +1333,10 @@ ratingsBody.addEventListener('click', handleRowRemoval); btnChangeCover.addEventListener('click', handleChangeCoverClick); coverInput.addEventListener('change', handleCoverChangeAsync); + document.addEventListener('click', handleTrackActionsMenuDismiss); + document.addEventListener('keydown', handleTrackActionsMenuDismiss); + window.addEventListener('scroll', handleTrackActionsMenuDismiss, true); + window.addEventListener('resize', handleTrackActionsMenuDismiss); document.addEventListener('DOMContentLoaded', InitializeAsync); // Register cleanup for these listeners. @@ -1181,6 +1358,11 @@ ratingsBody.removeEventListener('click', handleRowRemoval); btnChangeCover.removeEventListener('click', handleChangeCoverClick); coverInput.removeEventListener('change', handleCoverChangeAsync); + closeTrackActionsMenu(false); + document.removeEventListener('click', handleTrackActionsMenuDismiss); + document.removeEventListener('keydown', handleTrackActionsMenuDismiss); + window.removeEventListener('scroll', handleTrackActionsMenuDismiss, true); + window.removeEventListener('resize', handleTrackActionsMenuDismiss); document.removeEventListener('DOMContentLoaded', InitializeAsync); }); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml index 1b46d90e..f178db14 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Index.cshtml @@ -115,7 +115,8 @@ shuffle: '@_localizer["Shuffle"]', deleteItem: '@_localizer["Delete"]', deleteConfirm: '@_localizer["DeleteConfirm"]', - deleteFailed: '@_localizer["DeleteFailed"]' + deleteFailed: '@_localizer["DeleteFailed"]', + addToPlaylist: '@_localizer["AddToPlaylist"]' }; function buildItemsUrl() { @@ -252,6 +253,19 @@ if (artist.coverPath) shuffleAction.dataset.coverArtPath = artist.coverPath; + const addToPlaylistAction = document.createElement('a'); + addToPlaylistAction.setAttribute('role', 'menuitem'); + addToPlaylistAction.href = '#'; + addToPlaylistAction.className = 'card-action-add-to-playlist'; + addToPlaylistAction.textContent = jsLocalizedStrings.addToPlaylist; + addToPlaylistAction.addEventListener('click', async event => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeCardMenus(); + if (window.LuminaPlaylists) + await window.LuminaPlaylists.showAddScopeDialogAsync({ libraryId: libraryId, artistId: artist.id, title: artist.name || '', addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, returnFocus: trigger }); + }); + const deleteAction = document.createElement('a'); deleteAction.setAttribute('role', 'menuitem'); deleteAction.href = '#'; @@ -261,6 +275,7 @@ menu.appendChild(detailsAction); menu.appendChild(playAction); menu.appendChild(shuffleAction); + menu.appendChild(addToPlaylistAction); menu.appendChild(deleteAction); menu.addEventListener('click', async event => { diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml index 79c976ad..13e7eda0 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/AudioLibrary/MusicLibrary/Artists/Item.cshtml @@ -674,7 +674,8 @@ coverUploadFailed: @Json.Serialize(_localizer["CoverUploadFailed"].Value), play: @Json.Serialize(_localizer["Play"].Value), shuffle: @Json.Serialize(_localizer["Shuffle"].Value), - remove: @Json.Serialize(_localizer["Remove"].Value) + remove: @Json.Serialize(_localizer["Remove"].Value), + addToPlaylist: @Json.Serialize(_localizer["AddToPlaylist"].Value) }; // Reads the trimmed value of the element with the provided id. @@ -1127,10 +1128,20 @@ shuffleAction.setAttribute('data-audio-player-shuffle-scope', 'release'); applyAlbumPlayDescriptor(shuffleAction, album); + const addToPlaylistAction = createAlbumMenuAction(jsLocalizedStrings.addToPlaylist, 'card-action-add-to-playlist'); + addToPlaylistAction.addEventListener('click', async event => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeCardMenus(); + if (window.LuminaPlaylists) + await window.LuminaPlaylists.showAddScopeDialogAsync({ libraryId: libraryId, artistId: artistId, albumId: album.id, title: album.title || '', addToPlaylistLabel: jsLocalizedStrings.addToPlaylist, returnFocus: trigger }); + }); + const deleteAction = createAlbumMenuAction(jsLocalizedStrings.remove, 'card-action-delete'); menu.appendChild(playAction); menu.appendChild(shuffleAction); + menu.appendChild(addToPlaylistAction); menu.appendChild(deleteAction); menu.addEventListener('click', async event => { diff --git a/src/Lumina.Presentation.Web/Core/Views/Playlists/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Playlists/Index.cshtml new file mode 100644 index 00000000..2ba940cf --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Playlists/Index.cshtml @@ -0,0 +1,207 @@ +@* + FALLBACK PLAYLISTS PAGE - READ BEFORE EDITING + + This view is the application fallback of the playlists page, rendered only when the theme template of the page cannot be + loaded. On a healthy site the page comes from the theme's playlists/index template. It keeps the DOM contract and the client + script the theme template mirrors, so that listing and deleting playlists keep working even without the theme. + + The page only lists the playlists. Creating and editing a playlist happen on the dedicated playlist page, reached through + the create button or through a playlist card, the same way every other manageable resource of the application is split between a list page and an add/edit page. + + To restyle the page, edit the theme files. This fallback is intentionally plain, so that a broken theme is obvious to the user while the page still functions. + + /playlists +*@ + +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization +@using System +@using System.Collections.Generic +@using System.Text.Json +@using System.Text.Json.Serialization + +@inject IViewLocalizer _localizer +@inject IUrlService _urlService + +@{ + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + var strings = new Dictionary + { + ["title"] = _localizer["Title"].Value, + ["noPlaylists"] = _localizer["NoPlaylists"].Value, + ["tracks"] = _localizer["Tracks"].Value, + ["delete"] = _localizer["Delete"].Value, + ["deleteConfirm"] = _localizer["DeleteConfirm"].Value, + ["deleteFailed"] = _localizer["DeleteFailed"].Value, + ["items"] = _localizer["Items"].Value + }; + var jsonOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; +} + +@Html.AntiForgeryToken() + +
+
+
+
+
+

@_localizer["Title"]

+
+
+ + +
+
+ +
+
+
+ +@section Scripts { + + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Playlists/Item.cshtml b/src/Lumina.Presentation.Web/Core/Views/Playlists/Item.cshtml new file mode 100644 index 00000000..032310ce --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Playlists/Item.cshtml @@ -0,0 +1,1076 @@ +@* + FALLBACK PLAYLIST PAGE - READ BEFORE EDITING + + This view is the application fallback of a playlist page, rendered only when the theme template of the page cannot be + loaded. On a healthy site the page comes from the theme's playlists/item template. It keeps the DOM contract and the client + script the theme template mirrors, so that creating, editing, reordering, playing and deleting a playlist keep working + even without the theme. The same page serves the add route ({culture}/playlists/item) and the edit route + ({culture}/playlists/item/{playlistId}); the page data and the hidden 'isNew' flag tell the script which mode it is in. + + The rows render play triggers for the global audio player. The player handles those triggers by event delegation, so this + view binds no playback listener; the trigger attribute contract lives in docs/technical/theming/Theming.md. + + To restyle the page, edit the theme files. This fallback is intentionally plain, so that a broken theme is obvious to the user while the page still functions. + + /playlists/item + /playlists/item/{playlistId} +*@ + +@using Lumina.Presentation.Web.Common.DTO.Playlists +@using Lumina.Presentation.Web.Common.Services +@using Microsoft.AspNetCore.Mvc.Localization +@using System +@using System.Collections.Generic +@using System.Text.Json +@using System.Text.Json.Serialization + +@model PlaylistDto + +@inject IViewLocalizer _localizer +@inject IUrlService _urlService + +@{ + // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. + var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + var isNew = ViewData["IsNew"] as bool? ?? false; + var pageTitle = isNew ? _localizer["CreatePlaylist"].Value : Model.Name; + var strings = new Dictionary + { + ["play"] = _localizer["Play"].Value, + ["playPlaylist"] = _localizer["PlayPlaylist"].Value, + ["save"] = _localizer["Save"].Value, + ["saved"] = _localizer["Saved"].Value, + ["saveFailed"] = _localizer["SaveFailed"].Value, + ["delete"] = _localizer["Delete"].Value, + ["deleteConfirm"] = _localizer["DeleteConfirm"].Value, + ["deleteFailed"] = _localizer["DeleteFailed"].Value, + ["backToPlaylists"] = _localizer["BackToPlaylists"].Value, + ["tracks"] = _localizer["Tracks"].Value, + ["noTracks"] = _localizer["NoTracks"].Value, + ["addTrack"] = _localizer["AddTrack"].Value, + ["library"] = _localizer["Library"].Value, + ["artist"] = _localizer["Artist"].Value, + ["album"] = _localizer["Album"].Value, + ["track"] = _localizer["Track"].Value, + ["add"] = _localizer["Add"].Value, + ["addFailed"] = _localizer["AddFailed"].Value, + ["selectLibrary"] = _localizer["SelectLibrary"].Value, + ["selectArtist"] = _localizer["SelectArtist"].Value, + ["selectAlbum"] = _localizer["SelectAlbum"].Value, + ["selectTrack"] = _localizer["SelectTrack"].Value, + ["moveUp"] = _localizer["MoveUp"].Value, + ["moveDown"] = _localizer["MoveDown"].Value, + ["dragToReorder"] = _localizer["DragToReorder"].Value, + ["remove"] = _localizer["Remove"].Value, + ["removeConfirm"] = _localizer["RemoveConfirm"].Value, + ["removeFailed"] = _localizer["RemoveFailed"].Value, + ["reorderFailed"] = _localizer["ReorderFailed"].Value, + ["unavailableTrack"] = _localizer["UnavailableTrack"].Value, + ["playlistNameRequired"] = _localizer["PlaylistNameRequired"].Value, + ["nothingToPlay"] = _localizer["NothingToPlay"].Value, + ["playerUnavailable"] = _localizer["PlayerUnavailable"].Value, + ["editDetails"] = _localizer["EditDetails"].Value, + ["name"] = _localizer["Name"].Value, + ["description"] = _localizer["Description"].Value, + ["createPlaylist"] = _localizer["CreatePlaylist"].Value, + ["noMusicLibraries"] = _localizer["NoMusicLibraries"].Value, + ["loading"] = _localizer["Loading"].Value + }; + var jsonOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { new JsonStringEnumConverter() } + }; +} + +@Html.AntiForgeryToken() + +
+
+
+
+ + + +
+
+
+
+

@pageTitle

+
+
+

@_localizer["EditDetails"]

+ +
+
+ + *: +
+
+ +
+
+ +
+
+ : +
+
+ +
+
+ +
+ + @if (!isNew) + { + + + } + +
+
+
+
+ + @if (!isNew) + { + +
+
+
+

@_localizer["Tracks"]

+
+ + + +

@_localizer["AddTrack"]

+ +
+
+ : +
+
+
+
+ + +
+
+
@_localizer["SelectLibrary"]
+
+
+
+
+ +
+
+ : +
+
+
+
+ + +
+
+
@_localizer["SelectArtist"]
+
+
+
+
+ +
+
+ : +
+
+
+
+ + +
+
+
@_localizer["SelectAlbum"]
+
+
+
+
+ +
+
+ : +
+
+
+
+ + +
+
+
@_localizer["SelectTrack"]
+
+
+
+
+ +
+
+
+ + +
+
+
+
+ } +
+
+
+ +@section Scripts { + + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml index 193a433a..f7de8b66 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -31,7 +31,11 @@ - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-stop', '-previous', '-next', '-repeat', '-progress', '-progress-played', '-progress-downloaded', '-progress-undownloaded', '-current-time', '-total-time', '-track-name', '-album-name', '-now-playing-title', '-now-playing-release-type', '-now-playing-release', - '-now-playing-year', '-now-playing-artist', '-artwork-carousel', '-cover-thumbnail', '-cover-image', '-volume', '-volume-level', '-mute' and '-queue'. + '-now-playing-year', '-now-playing-artist', '-artwork-carousel', '-cover-thumbnail', '-cover-image', '-volume', '-volume-level', '-mute', '-queue', '-playlist-combobox' and '-add-queue-to-playlist'. + The queue-to-playlist action is a standard application combo box, so a theme renders the usual 'enlightenment-combobox' + markup and puts the '-playlist-combobox' hook on its root. The player only reads the 'data-value' of the selected text + when the add button is pressed. A theme that renders one half of the action gets a complete built-in pair, placed in a + queue area wrapper above the queue so that it never becomes a new column of the expanded layout. The volume fill element ('-volume-level') is a styling hook the stylesheet drives from the custom properties below, not one the script writes to. The repeat toggle carries 'data-audio-player-repeat' and the player writes 'data-audio-player-repeat-mode' ('off', 'all' or 'one') and toggles the 'is-active' and 'is-one' classes on it. @@ -80,7 +84,23 @@
-
    +
    +
    +
    +
    + + +
    +
    +
    @localizer["AudioPlayerSelectPlaylist"]
    +
    +
    + +
    +
      +
      diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index af26abf3..f833e521 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -56,6 +56,10 @@ // The endpoint that draws a uniformly random batch of tracks of a library, artist or album. The server samples the // database, so a shuffle of a large library never has to enumerate its albums and tracks in the browser. shuffleTracksUrl: '@_urlService.GetRelativeUrl(WebRoutes.Music.SHUFFLE_TRACKS)', + // The playlists of the user, and the route that appends the current queue to one of them. The queue action in the + // expanded bar uses the first to fill its select and the second to send the ordered track Ids in one request. + getPlaylistsUrl: '@_urlService.GetRelativeUrl(WebRoutes.Playlists.GET_PLAYLISTS)', + addPlaylistEntriesRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Playlists.ADD_PLAYLIST_ENTRIES, new { playlistId = default(Guid) })', strings: { play: '@localizer["AudioPlayerPlay"]', pause: '@localizer["AudioPlayerPause"]', @@ -71,7 +75,33 @@ repeatAll: '@localizer["AudioPlayerRepeatAll"]', repeatOne: '@localizer["AudioPlayerRepeatOne"]', queue: '@localizer["AudioPlayerQueue"]', - albumArtwork: '@localizer["AudioPlayerAlbumArtwork"]' + albumArtwork: '@localizer["AudioPlayerAlbumArtwork"]', + addQueueToPlaylist: '@localizer["AudioPlayerAddQueueToPlaylist"]', + selectPlaylist: '@localizer["AudioPlayerSelectPlaylist"]', + playlistQueueAdded: '@localizer["AudioPlayerPlaylistQueueAdded"]', + playlistQueueAddFailed: '@localizer["AudioPlayerPlaylistQueueAddFailed"]', + noPlaylists: '@localizer["AudioPlayerNoPlaylists"]', + add: '@localizer["AudioPlayerAdd"]', + addToPlaylist: '@localizer["PlaylistAddToPlaylist"]' + } + }; + // The endpoints and dialog labels of the add-to-playlist actions that the music library, artist and album cards share. The route + // that returns the track Ids of a scope lets a whole library, artist or album be added in one batch request, and the batch + // route is the same one the player uses for its queue. The routes are culture aware web routes, so the pages never hardcode + // a path, and the dialog labels come from the global resources. + var playlistConfiguration = { + getPlaylistsUrl: '@_urlService.GetRelativeUrl(WebRoutes.Playlists.GET_PLAYLISTS)', + addPlaylistEntryUrl: '@_urlService.GetRelativeUrl(WebRoutes.Playlists.ADD_PLAYLIST_ENTRY, new { playlistId = default(Guid) })', + addScopeEntriesUrl: '@_urlService.GetRelativeUrl(WebRoutes.Playlists.ADD_PLAYLIST_SCOPE_ENTRIES, new { playlistId = default(Guid) })', + createPlaylistUrl: '@_urlService.GetRelativeUrl(WebRoutes.Playlists.ADD)', + strings: { + selectPlaylist: '@localizer["AudioPlayerSelectPlaylist"]', + noPlaylists: '@localizer["AudioPlayerNoPlaylists"]', + createPlaylist: '@localizer["PlaylistCreate"]', + tracksAdded: '@localizer["PlaylistTracksAdded"]', + tracksAddFailed: '@localizer["PlaylistTracksAddFailed"]', + noTracksToAdd: '@localizer["PlaylistNoTracksToAdd"]', + add: '@localizer["AudioPlayerAdd"]' } }; @@ -87,6 +117,7 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index 2b7352bd..f9bfa459 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -1202,6 +1202,115 @@ body { width: 64px; } + .tracks-table .track-play-column, + .tracks-table .track-actions-column { + width: 40px; + } + + .tracks-table .track-play-cell, + .tracks-table .track-actions-cell { + width: 40px; + padding-left: 0; + padding-right: 0; + text-align: center; + } + +/* The play control of an album track row stays a small square, so its column cannot widen the table. */ +.track-play-button { + width: 24px; + min-width: 24px; + height: 24px; + padding: 0; + line-height: 1; +} + +/* The card actions menu, reused by the actions menu of an album track row. */ +.card-actions-trigger { + position: absolute; + right: 2px; + bottom: 28px; + width: 22px; + height: 22px; + display: none; + align-items: center; + justify-content: center; + cursor: pointer; + color: #6DCBFE; + border: 1px solid #777777; + border-bottom-color: #000000; + border-right-color: #000000; + background: linear-gradient(to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100%); + font-size: 16px; + line-height: 1; +} + +.card-actions-trigger::after { + content: '\22EE'; +} + +.media-card:hover .card-actions-trigger, +.media-card.open .card-actions-trigger { + display: flex; +} + +.card-actions-trigger:hover { + color: #FFFFFF; +} + +/* The track row places the same trigger inline and always visible, instead of on a media card. */ +.track-actions-cell .card-actions-trigger { + position: static; + display: flex; + margin: 0 auto; +} + +.card-actions-menu { + display: none; + position: fixed; + z-index: 901; + min-width: 150px; + background: #4F4F4F; + border: 1px solid #777777; + border-bottom-color: #000000; + border-right-color: #000000; + padding: 4px; + margin: 0; + list-style-type: none; +} + +.media-card.open .card-actions-menu, +.card-actions-menu.open { + display: block; +} + +.card-actions-menu a { + display: block; + padding: 3px 10px; + text-decoration: none; + cursor: default; + color: #6DCBFE; + background: #232323; + border-left: 1px solid #000000; + border-right: 1px solid #777777; + user-select: none; +} + +.card-actions-menu a:first-child { + border-top: 1px solid #000000; +} + +.card-actions-menu a:last-child { + border-bottom: 1px solid #777777; +} + +.card-actions-menu a:hover { + background: linear-gradient(to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100%); + border: 1px solid #777777; + border-right-color: #000000; + border-bottom-color: #000000; + color: #FFFFFF; +} + .track-name-link { text-decoration: none; color: #E6E6E6; @@ -1778,8 +1887,38 @@ html.audio-player-initializing .audio-player-container { display: none; } +/* The queue area takes the flex slot of the queue itself, so the queue action row above the list never becomes a new + sibling column of the expanded layout. The queue keeps filling the remaining height inside the area. */ +.audio-player-queue-area { + display: flex; + flex: 1 1 auto; + flex-direction: column; + min-width: 0px; + min-height: 0px; +} + +.audio-player-queue-actions { + display: flex; + flex: 0 0 auto; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding-bottom: 8px; +} + +.audio-player-queue-actions .enlightenment-combobox { + flex: 1 1 200px; + min-width: 160px; +} + +.audio-player-queue-actions .enlightenment-combobox.is-disabled { + opacity: 0.6; + pointer-events: none; +} + .audio-player-queue { flex: 1 1 auto; + min-height: 0px; margin: 0px; padding: 0px; overflow-y: auto; @@ -1835,3 +1974,40 @@ html.audio-player-initializing .audio-player-container { color: #9AA7B0; font-variant-numeric: tabular-nums; } + +/* The shared playlist picker of the add-to-playlist card actions. It reuses the application dialog surface on its own + overlay, so it never takes part in the queue of the global dialog service. */ +.playlist-picker-overlay { + position: fixed; + inset: 0; + z-index: 1000; + display: flex; + align-items: center; + justify-content: center; + padding: 16px; + background-color: rgba(0, 0, 0, 0.6); +} + +.playlist-picker-overlay .dialog { + width: 400px; + max-width: 100%; +} + +.playlist-picker-body { + padding-top: 4px; +} + +.playlist-picker-scope { + margin: 0px 0px 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: #9AA7B0; + font-size: 12px; +} + +.playlist-picker-empty { + margin: 10px 0px 0px; + color: #9AA7B0; + font-size: 12px; +} diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index 885d4dd2..f2b93e64 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -9,7 +9,9 @@ * public API. The download, decode and render pipeline is plugged in as a swappable engine. The bar holds * the three state progress bar (played, downloaded but not played, and not yet downloaded), the volume and mute * controls, the keyboard shortcuts, and the loading state a seek into a not yet downloaded position shows; the volume - * and mute the controls change are persisted to the stored playback state of the user on their own. + * and mute the controls change are persisted to the stored playback state of the user on their own. The expanded bar also + * offers appending the current queue, in order, to one of the playlists of the user, through a theme hook with a built-in + * fallback when the theme does not render it. * * Public control API (window.LuminaAudioPlayer.instance) * ---------------------------------------- @@ -21,6 +23,8 @@ * option starts a random track of that context instead of its first track. * - playNextAsync(descriptor): queues a track or an album after the current entry, without starting playback. It * discards the pending autoplay continuation, because an explicit play next is a manual queue. + * - appendToQueueAsync(descriptor): appends a track or a context at the end of the queue, without starting playback. It + * discards the pending autoplay continuation. When nothing is current, it starts the descriptor. * - playShuffledAsync(descriptor, scope): starts the described context and turns shuffle on for the given scope. When the * scope is omitted, it shuffles the release of the started context. * - playLibraryShuffledAsync(libraryId): starts a shuffled playback of a whole media library, drawing the first track @@ -702,6 +706,11 @@ this.dom = {}; // The raw theme sub templates of the dynamic content, read once with the bar elements and null when the theme does not provide them. this.subTemplates = { queueItem: null, playlistItem: null }; + // The playlists of the user, used by the control that adds the current queue to a playlist, and the in flight load of + // them, so an expansion and a focus on the select share one request instead of racing each other. + this.playlists = []; + this.playlistsLoadPromise = null; + this.isAddingQueueToPlaylist = false; this.descriptorClickHandler = null; this.controlHandlers = []; this.isProgressRenderScheduled = false; @@ -801,6 +810,10 @@ queueItem: readSubTemplate('audio-player-template-queue-item'), playlistItem: readSubTemplate('audio-player-template-playlist-item') }; + // The queue action that adds the current queue to a playlist is a theme hook. A theme that does not render it gets the + // built-in control, placed in a queue area wrapper above the queue, exactly as a missing queue item sub template falls back + // to built-in markup. The wrapper takes the flex slot of the queue, so the action never becomes an extra column. + this.ensurePlaylistControls(); } /** @@ -837,6 +850,12 @@ } if (this.dom.mute) this.addControlHandler(this.dom.mute, 'click', () => this.toggleMuteAsync()); + if (this.dom.addQueueToPlaylistButton) + this.addControlHandler(this.dom.addQueueToPlaylistButton, 'click', () => this.addQueueToPlaylistAsync()); + if (this.dom.playlistCombobox) + // Loading on the first focus makes the control usable without waiting for an expansion. The shared load + // promise makes a focus and an expansion that happen together issue one request. + this.addControlHandler(this.dom.playlistCombobox, 'focusin', () => this.loadPlaylistsAsync()); } /** @@ -1892,6 +1911,10 @@ this.scrollQueueToCurrentEntry(); // The album details are only needed by the expanded view, so a collapsed player does not request them. this.renderNowPlayingDetails(); + // The playlist choices are only visible in the expanded view, so they are loaded when it opens. The load is shared + // with a focus of the combo box, and a failure leaves the playlists the bar already knows. It is deliberately + // not awaited: the bar must expand immediately, and the action stays disabled until the choices arrive. + this.loadPlaylistsAsync(); } else this.cancelNowPlayingDetailsRequest(); return isExpanded; @@ -2359,6 +2382,78 @@ return true; } + /** + * Appends a descriptor or the tracks of a context at the end of the current queue, as an explicit add to queue action. + * + * The pending autoplay continuation is discarded, because an explicit add to queue is a manual queue: the user chose + * what should follow the entries already queued, so autopicking more of the album or artist would override that choice. + * When nothing is current there is no queue to append to, so the descriptor is started instead. + * + * Unlike playNextAsync, which reserves the slot right after the current entry, this appends after everything the user + * already queued. Both are explicit manual queue actions, so both discard the pending autoplay continuation. + * @param {Object} descriptorInput - The play descriptor to append, per {@link LuminaAudioPlayer.createPlayDescriptor}. + * @returns {Promise} True when at least one entry was appended, or when playback started because the queue was empty. + */ + async appendToQueueAsync(descriptorInput) { + if (!this.isAvailable) + return false; + const descriptor = createPlayDescriptor(descriptorInput); + if (!descriptor) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, 'The play descriptor identifies no library, or no playable context.')); + return false; + } + // The queue is empty, so there is nothing to append to. Starting the descriptor is the only useful outcome. + if (this.queue.entries.length === 0) + return this.playAsync(descriptor); + // An explicit add to queue is a later user action than a shuffle that is still resolving, so the shuffle is cancelled and cannot replace the queue under the manual item. + this.cancelPendingShuffle(); + const generation = this.queueGeneration; + // A context build that still owns the player is the play request the manual item belongs to. Appending to the + // queue it is about to replace would lose the item, so it is refused while that build owns the player. + const pendingContextToken = this.state === LuminaAudioPlayer.PlayerState.LOADING && this.playContextBuildHandle !== null + ? this.playRequestToken + : null; + const buildHandle = this.openPlayNextBuild(); + // Appending also resolves its descriptor asynchronously, so it reuses the play-next build handle for the same + // timeout, abort and cleanup rules. Only the place where the resolved entries are inserted differs. + let descriptors; + try { + descriptors = (await this.queueService.buildQueueAsync(descriptor, buildHandle.signal)).descriptors; + } catch (error) { + if (buildHandle.signal && buildHandle.signal.aborted) { + if (buildHandle.timedOut) + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.QUEUE_LOAD_FAILED, 'The track to append could not be loaded in time.')); + return false; + } + if (error && error.details && error.details.reason === LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED) + return false; + this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.QUEUE_LOAD_FAILED); + return false; + } finally { + this.closePlayNextBuild(buildHandle); + } + if (descriptors.length === 0) + return false; + if (pendingContextToken !== null && this.playRequestToken === pendingContextToken && this.playContextBuildHandle !== null) + return false; + // A new play request replaced the queue while the item was resolved, so the item belongs to a queue the user already left and must not be appended to the new one. + const isOwnedContextResolution = pendingContextToken !== null && this.playRequestToken === pendingContextToken; + if (generation !== this.queueGeneration && !isOwnedContextResolution) + return false; + // A handoff the engine already prepared from the continuation is dropped, so the explicit item is truly queued after the entries the user already had. + await this.cancelUpcomingTransitionAsync(); + if (generation !== this.queueGeneration && !isOwnedContextResolution) + return false; + this.queue.removePendingContinuation(); + const appended = this.queue.append(descriptors, 'manual'); + if (appended === 0) + return false; + this.renderQueue(); + this.renderQueueControls(); + this.emitQueueStateChanged(); + return true; + } + /** * Inserts the explicit play next items that waited for a play context to resolve. The items belong to one play * request, so a newer request discards them instead of applying an old user action to a different queue. @@ -4350,6 +4445,326 @@ if (label) this.dom.repeat.setAttribute('aria-label', label); } + // The queue-to-playlist action depends on whether the queue has an entry, so it is refreshed with the rest of + // the queue controls. + this.updatePlaylistControlsState(); + } + + /** + * Finds the theme hooks of the queue-to-playlist action, or builds the built-in control when the theme does not provide it. + * + * The action belongs to the queue column, because it acts on the queue the expanded bar shows. A theme may render the + * documented combobox hook and button, in which case both are used as they are. When either is missing, both are replaced + * with the built-in pair, so a theme never ends up with half of an action. The built-in pair is placed in a queue area + * wrapper around the queue, never as a new sibling column of the expanded layout, so it does not take horizontal space + * away from the queue. A theme that places its own hooks is responsible for the same layout decision. + */ + ensurePlaylistControls() { + if (!this.container) + return; + const existingCombobox = this.container.querySelector('[data-audio-player-playlist-combobox]'); + const existingButton = this.container.querySelector('[data-audio-player-add-queue-to-playlist]'); + if (existingCombobox && existingButton) { + // Both hooks are present, so the theme owns the markup and the layout; the player only binds behavior. + this.dom.playlistCombobox = existingCombobox; + this.dom.addQueueToPlaylistButton = existingButton; + return; + } + if (!this.dom.queue || !this.dom.queue.parentElement) + return; + // A lone hook cannot complete the action: a button without a combobox has nothing to add to, and a combobox + // without a button cannot submit. Replace the half pair so the theme never renders a dead control. + if (existingCombobox) + existingCombobox.remove(); + if (existingButton) + existingButton.remove(); + + const strings = this.getStrings(); + const queue = this.dom.queue; + let area = queue.parentElement; + // The expanded layout is a grid of columns. Inserting the action as a sibling would add a new column and + // take width from the queue, so the queue and the action share the queue's column through this wrapper. + if (!area.classList.contains('audio-player-queue-area')) { + area = document.createElement('div'); + area.className = 'audio-player-queue-area'; + queue.parentElement.insertBefore(area, queue); + area.appendChild(queue); + } + + const actions = document.createElement('div'); + actions.className = 'audio-player-queue-actions audio-player-queue-actions-fallback'; + + const combobox = this.createPlaylistCombobox(strings); + // The fallback button carries the same data attribute and class as the theme hook, so the existing binding and + // the theme styling work with either markup. + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'confirm-button h-22px audio-player-add-queue-to-playlist'; + button.setAttribute('data-audio-player-add-queue-to-playlist', ''); + button.textContent = strings.addToPlaylist || strings.add || strings.addQueueToPlaylist || '+'; + if (strings.addQueueToPlaylist) + button.setAttribute('aria-label', strings.addQueueToPlaylist); + + actions.appendChild(combobox); + actions.appendChild(button); + area.insertBefore(actions, queue); + this.dom.playlistCombobox = combobox; + this.dom.addQueueToPlaylistButton = button; + } + + /** + * Builds the built-in playlist chooser with the same markup and behavior as every other combo box in the application: a + * checkbox toggle, a selected text span that carries the value in 'data-value', and a dropdown of options. The global site + * script updates the selected text and closes the dropdown when an option is clicked, so the player only reads the value. + * @param {Object} strings - The localized strings of the player. + * @returns {HTMLElement} The combo box root. + */ + createPlaylistCombobox(strings) { + const combobox = document.createElement('div'); + combobox.className = 'enlightenment-combobox audio-player-queue-playlist-combobox'; + combobox.setAttribute('data-audio-player-playlist-combobox', ''); + if (strings.addQueueToPlaylist) + combobox.setAttribute('aria-label', strings.addQueueToPlaylist); + + const shine = document.createElement('div'); + shine.className = 'shine-effect'; + shine.style.top = '1px'; + combobox.appendChild(shine); + + const toggleId = 'audio-player-playlist-combobox-toggle'; + // The player is a singleton in the layout, so the fixed id cannot collide with a second built-in picker. + const toggle = document.createElement('input'); + toggle.type = 'checkbox'; + toggle.id = toggleId; + toggle.className = 'enlightenment-toggle-checkbox'; + combobox.appendChild(toggle); + + const label = document.createElement('label'); + label.className = 'enlightenment-toggle'; + label.htmlFor = toggleId; + const selected = document.createElement('span'); + selected.className = 'enlightenment-selected-text'; + selected.setAttribute('data-value', ''); + selected.textContent = strings.selectPlaylist || ''; + label.appendChild(selected); + combobox.appendChild(label); + + const dropdown = document.createElement('div'); + dropdown.className = 'enlightenment-dropdown'; + const dropdownShine = document.createElement('div'); + dropdownShine.className = 'shine-effect'; + dropdownShine.style.top = '-4px'; + dropdown.appendChild(dropdownShine); + const placeholder = document.createElement('div'); + placeholder.className = 'enlightenment-option first-option disabled'; + placeholder.setAttribute('data-value', ''); + placeholder.textContent = strings.selectPlaylist || ''; + dropdown.appendChild(placeholder); + combobox.appendChild(dropdown); + // The player deliberately does not bind option clicks. The global site script owns opening, closing and copying + // the chosen option into data-value; the player only reads the selected value when the action is pressed. + return combobox; + } + + /** + * Refreshes the enabled state of the queue-to-playlist action. + * + * The action needs a queue to send and at least one playlist to send it to, so it is disabled while either is + * missing, and while a request is already in flight, which prevents the same queue from being appended twice by + * a double click. The combobox has different rules: choosing a playlist is harmless without a queue, and the user + * may pick one before starting playback, so it is only disabled while an add is in flight. + */ + updatePlaylistControlsState() { + const isBusy = this.isAddingQueueToPlaylist === true; + // Without a queue or a playlist, pressing the action could only produce an error. + const isDisabled = isBusy || this.queue.entries.length === 0 || this.playlists.length === 0; + if (this.dom.addQueueToPlaylistButton) { + this.dom.addQueueToPlaylistButton.disabled = isDisabled; + this.dom.addQueueToPlaylistButton.classList.toggle('is-disabled', isDisabled); + } + if (this.dom.playlistCombobox) { + // The combobox is disabled only while a request is in flight; its list can be selected before a queue exists. + const toggle = this.dom.playlistCombobox.querySelector('.enlightenment-toggle-checkbox'); + if (toggle) + toggle.disabled = isBusy; + this.dom.playlistCombobox.classList.toggle('is-disabled', isBusy); + } + } + + /** + * Loads the playlists of the current user into the queue action combo box. The request is shared by every caller, so a + * focus and an expansion that happen together issue one request, and the choices are refreshed every time the expanded bar + * opens, because a playlist may have been created or deleted on another page since the last opening. + * @returns {Promise} A promise that completes when the choices were refreshed or the request settled. + */ + async loadPlaylistsAsync() { + if (!this.dom.playlistCombobox) + return; + // A focus and an expansion can call this together. Sharing the in-flight promise avoids two requests and two + // dropdown rebuilds that would race each other. + if (this.playlistsLoadPromise) + return this.playlistsLoadPromise; + const configuration = this.getConfiguration(); + const url = configuration && configuration.getPlaylistsUrl; + if (!url) + return; + + this.playlistsLoadPromise = (async () => { + const playlists = await this.fetchJsonAsync(url, null, 'the playlists request'); + // A redirect means the session expired and the page is navigating, and undefined means the request failed. + // In both cases keeping the choices the bar already knows is better than replacing them with an empty dropdown. + if (playlists === REDIRECTED || playlists === undefined) + return; + this.playlists = Array.isArray(playlists) ? playlists : []; + const combobox = this.dom.playlistCombobox; + if (!combobox) + return; + const selected = combobox.querySelector('.enlightenment-selected-text'); + const dropdown = combobox.querySelector('.enlightenment-dropdown'); + if (!selected || !dropdown) + return; + const strings = this.getStrings(); + // Remember the selected playlist by id, not by position: the list can be reordered or shortened by a + // deletion made on another page. + const previous = selected.getAttribute('data-value') || ''; + const placeholderText = this.playlists.length === 0 + ? (strings.noPlaylists || strings.selectPlaylist || '') + : (strings.selectPlaylist || ''); + // Keep the decorative shine element; only the option rows are rebuilt, so the dropdown keeps the structure + // the global site script expects. + for (const child of Array.from(dropdown.children)) { + if (!child.classList.contains('shine-effect')) + child.remove(); + } + const placeholder = document.createElement('div'); + placeholder.className = 'enlightenment-option first-option disabled'; + placeholder.setAttribute('data-value', ''); + placeholder.textContent = placeholderText; + dropdown.appendChild(placeholder); + let selectedPlaylist = null; + for (let index = 0; index < this.playlists.length; index++) { + const playlist = this.playlists[index]; + const option = document.createElement('div'); + option.className = 'enlightenment-option' + (index === this.playlists.length - 1 ? ' last-option' : ''); + option.setAttribute('data-value', String(playlist.id)); + option.textContent = playlist.name || ''; + dropdown.appendChild(option); + if (String(playlist.id) === previous) + selectedPlaylist = playlist; + } + if (selectedPlaylist) { + selected.textContent = selectedPlaylist.name || ''; + selected.setAttribute('data-value', String(selectedPlaylist.id)); + } else { + // The selected playlist no longer exists. Clear the selection instead of leaving a stale id that the + // server would reject when the user presses Add. + selected.textContent = placeholderText; + selected.setAttribute('data-value', ''); + } + // The action depends on whether the user has any playlist, so refresh it after the list is replaced. + this.updatePlaylistControlsState(); + })().finally(() => { + this.playlistsLoadPromise = null; + }); + return this.playlistsLoadPromise; + } + + /** + * Appends the current queue to the selected playlist, in queue order, including repeated tracks. + * + * The whole queue is sent as one request, so a queue that references a track that disappeared or moved out of reach is rejected + * as a whole instead of leaving a part of the queue in the playlist. A success or failure is reported with the global notification service when the page provides it. + * @returns {Promise} A promise that completes when the add settled. + */ + async addQueueToPlaylistAsync() { + // A second click while the first request is in flight would append the same queue twice. The flag makes the + // action single-flight; the controls below are disabled for the same reason. + if (this.isAddingQueueToPlaylist) + return; + const strings = this.getStrings(); + const combobox = this.dom.playlistCombobox; + if (!combobox) + return; + const selected = combobox.querySelector('.enlightenment-selected-text'); + const playlistId = selected ? (selected.getAttribute('data-value') || '') : ''; + if (!playlistId) { + // The placeholder row is selectable in the markup but carries an empty value; it means no playlist is chosen. + this.showPlaylistNotification(strings.selectPlaylist, true); + return; + } + // Only entries that reference a track can be addressed by the playlist entry route. A queue can contain entries + // without a track id; sending one would make the whole request fail, so they are filtered out here. + const trackIds = this.queue.entries + .map(entry => entry.descriptor && entry.descriptor.trackId) + .filter(trackId => typeof trackId === 'string' && trackId.length > 0); + if (trackIds.length === 0) { + this.showPlaylistNotification(strings.playlistQueueAddFailed, true); + return; + } + const configuration = this.getConfiguration(); + const routeTemplate = configuration && configuration.addPlaylistEntriesRouteTemplate; + if (!routeTemplate) { + // The layout renders the route template with an empty Guid. Without it there is no URL to post to. + this.showPlaylistNotification(strings.playlistQueueAddFailed, true); + return; + } + const url = routeTemplate.replace('00000000-0000-0000-0000-000000000000', encodeURIComponent(playlistId)); + this.isAddingQueueToPlaylist = true; + this.updatePlaylistControlsState(); + try { + const addedEntries = await this.postJsonAsync(url, { trackIds: trackIds }, { label: 'the add queue to playlist request' }); + // The session expired and the page is navigating. The add did not happen, but a failure notification during + // the navigation would be noise. + if (addedEntries === REDIRECTED) + return; + if (addedEntries) { + // The queue is server-owned content now. The player leaves its local queue untouched and announces the + // result so an open playlist page can refresh its window. + this.showPlaylistNotification(strings.playlistQueueAdded, false); + this.notifyPlaylistUpdated(addedEntries); + } else + this.showPlaylistNotification(strings.playlistQueueAddFailed, true); + } finally { + // Always clear the busy state and re-enable the controls, including after a failure, so the user can retry. + this.isAddingQueueToPlaylist = false; + this.updatePlaylistControlsState(); + } + } + + /** + * Announces the playlist that the queue was added to, so an open playlist page can refresh it. + * + * The player is global and must not import a page module. A DOM event lets any interested page refresh itself + * without creating a direct dependency between the player and the playlist page. + * @param {Object} addedEntries - The minimal result with the playlist Id, the added count and the activity time. + */ + notifyPlaylistUpdated(addedEntries) { + // CustomEvent and document are absent in some non-browser test hosts; the announcement is optional there. + if (!addedEntries || typeof document === 'undefined' || typeof CustomEvent !== 'function') + return; + document.dispatchEvent(new CustomEvent('lumina:playlist-updated', { detail: addedEntries })); + } + + /** + * Shows a notification for the queue-to-playlist action when the page provides the global notification service. + * + * The service is global but not guaranteed on every page or test host. The console fallback keeps a failure + * visible without throwing from a player action, which would leave the controls stuck in their busy state. + * @param {string} message - The localized message to show. + * @param {boolean} isError - True to show the message as an error, false for a success. + */ + showPlaylistNotification(message, isError) { + if (!message) + return; + if (typeof notificationService !== 'undefined' && typeof NotificationType !== 'undefined') { + notificationService.show(message, isError ? NotificationType.ERROR : NotificationType.SUCCESS); + return; + } + // Minimal pages and tests may not load the notification service; a console entry is still useful and safe. + if (isError) + console.error(`Audio player: ${message}`); + else + console.info(`Audio player: ${message}`); } /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/playlists.js b/src/Lumina.Presentation.Web/wwwroot/js/playlists.js new file mode 100644 index 00000000..c94b356b --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/playlists.js @@ -0,0 +1,449 @@ +/** + * Shared add-to-playlist actions for the music library, artist and album cards, and for the player queue. + * + * The module owns one modal playlist picker. A page opens it with the scope or the single track it wants to add. A scope + * is resolved by the server into its ordered track Ids and appended in one request; a single track is appended through + * the single entry route. The actual card and track menu items are small wrappers that give the menu item its scope and + * call LuminaPlaylists.showAddScopeDialogAsync. + * + * The scope is resolved on the server so the browser never enumerates a whole library, and the server can add all of its + * tracks to the playlist atomically. A single track is already identified, so it uses the cheaper single-entry route + * instead. The picker is built here, not rendered by each page, so the cards, the album and artist pages and the player + * all share one dialog, one focus behavior and one error path. After a successful add the module dispatches the + * `lumina:playlist-updated` DOM event: an open playlist page can refresh itself, while the callers stay decoupled from it. + */ +(function () { + 'use strict'; + + // The layout renders the playlist id of the route as an empty Guid because the id is not known until the user picks + // a playlist here. Replacing this sentinel keeps the route construction in one place and avoids hand-built paths. + const EMPTY_GUID = '00000000-0000-0000-0000-000000000000'; + // The picker ids must be unique per dialog, because the toggle and the title are linked by id. The sequence makes a + // second dialog safe even if a previous one was removed abruptly. + let pickerSequence = 0; + // Only one picker may be open: two overlays would compete for Escape and focus, and the user could add to two + // different playlists. This holds the close function and the overlay of the current one. + let activePicker = null; + + /** + * Gets the playlist configuration the layout renders for every page. + * + * The configuration is the only contract between the layout and this module: it carries the routes and the localized + * labels. Reading it lazily, instead of capturing it when the script loads, lets the layout render the configuration + * after this deferred script has been parsed. + * @returns {Object|null} The configuration, or null when the layout did not render it. + */ + function getConfiguration() { + return window.playlistConfiguration || null; + } + + /** + * Gets the localized strings of the playlist actions, with empty values when the layout did not render them. + * @returns {Object} The localized strings. + */ + function getStrings() { + const configuration = getConfiguration(); + return configuration && configuration.strings ? configuration.strings : {}; + } + + /** + * Shows a success or error notification through the global notification service, with a console fallback. + * + * The notification service is provided by the layout, but the module must not assume it exists: it is also loaded + * on minimal pages and in test hosts. Falling back to the console keeps a failure visible without throwing from a + * UI action, which would leave the picker stuck in its busy state. + * @param {string} message - The localized message to show. + * @param {boolean} isError - True to show an error, false for a success. + */ + function showNotification(message, isError) { + if (!message) + return; + if (typeof notificationService !== 'undefined' && typeof NotificationType !== 'undefined') { + notificationService.show(message, isError ? NotificationType.ERROR : NotificationType.SUCCESS); + return; + } + if (isError) + console.error(`Playlists: ${message}`); + else + console.info(`Playlists: ${message}`); + } + + /** + * Builds the standard application combo box used to pick a playlist. + * + * The application has one combobox contract: the markup below is styled by the global stylesheet, and the global + * site script handles opening, closing and copying the clicked option into the selected text. The module must not + * add its own selection logic on top of that, or the two would fight. It builds the same structure a Razor view + * would render, so the picker looks and behaves like every other select in the application. + * @param {string} id - The unique root Id of the combo box. + * @param {string} placeholder - The placeholder shown before a playlist is selected. + * @returns {Object} The combo box elements. + */ + function createCombobox(id, placeholder) { + const root = document.createElement('div'); + root.className = 'enlightenment-combobox w-100'; + root.id = id; + + // The shine elements are purely decorative. They are kept when the options are rebuilt, so the dropdown does not + // flicker or lose its inset shadow while the playlist request refreshes the rows. + const shine = document.createElement('div'); + shine.className = 'shine-effect'; + shine.style.top = '1px'; + root.appendChild(shine); + + const toggle = document.createElement('input'); + toggle.type = 'checkbox'; + toggle.className = 'enlightenment-toggle-checkbox'; + toggle.id = `${id}-toggle`; + root.appendChild(toggle); + + const label = document.createElement('label'); + label.className = 'enlightenment-toggle'; + label.htmlFor = toggle.id; + const selected = document.createElement('span'); + selected.className = 'enlightenment-selected-text'; + selected.setAttribute('data-value', ''); + selected.textContent = placeholder; + label.appendChild(selected); + root.appendChild(label); + + const dropdown = document.createElement('div'); + dropdown.className = 'enlightenment-dropdown'; + const dropdownShine = document.createElement('div'); + dropdownShine.className = 'shine-effect'; + dropdownShine.style.top = '-4px'; + dropdown.appendChild(dropdownShine); + // The disabled first option is the "nothing selected" row the global combobox script expects. It also gives + // the dropdown a stable first child when the user has no playlists yet. + const firstOption = document.createElement('div'); + firstOption.className = 'enlightenment-option first-option disabled'; + firstOption.setAttribute('data-value', ''); + firstOption.textContent = placeholder; + dropdown.appendChild(firstOption); + root.appendChild(dropdown); + + return { root, selected, dropdown, toggle }; + } + + /** + * Fills the playlist combo box with the playlists of the user. + * + * Only the option rows are replaced. The first option and the decorative elements are kept because the global site + * script and the stylesheet rely on them, and rebuilding the whole dropdown would reset its open state and focus. + * @param {Object} combobox - The combo box elements. + * @param {Array} playlists - The playlists to list. + * @param {string} placeholder - The placeholder shown before a playlist is selected. + */ + function fillPlaylists(combobox, playlists, placeholder) { + combobox.selected.textContent = placeholder; + combobox.selected.setAttribute('data-value', ''); + combobox.dropdown.querySelectorAll('.enlightenment-option:not(.first-option)').forEach(option => option.remove()); + const firstOption = combobox.dropdown.querySelector('.first-option'); + if (firstOption) { + firstOption.textContent = placeholder; + firstOption.setAttribute('data-value', ''); + } + for (const playlist of playlists) { + // A malformed entry has no id to send to the server and no value to select. Skipping it keeps the rest of + // the dialog usable instead of rendering an option that cannot be added to. + if (!playlist || !playlist.id) + continue; + const option = document.createElement('div'); + option.className = 'enlightenment-option'; + option.setAttribute('data-value', String(playlist.id)); + option.textContent = playlist.name || ''; + combobox.dropdown.appendChild(option); + } + // The stylesheet rounds the last row; it must be recomputed whenever the list changes, because the previous + // last row becomes an ordinary row. + const options = combobox.dropdown.querySelectorAll('.enlightenment-option:not(.first-option)'); + options.forEach((option, index) => option.classList.toggle('last-option', index === options.length - 1)); + } + + /** + * Builds the scope add route of a playlist by replacing the empty Id placeholder with the selected playlist Id. + * + * The layout renders the route with an empty Guid because the playlist is not known until the user picks one. The + * id is encoded so it stays a single path segment even if the DOM value is malformed. + * @param {string} playlistId - The Id of the selected playlist. + * @returns {string} The route that appends the scope to the playlist. + */ + function buildScopeAddUrl(playlistId) { + const configuration = getConfiguration(); + const template = configuration ? configuration.addScopeEntriesUrl : ''; + if (typeof template !== 'string' || template.length === 0) + return ''; + return template.replace(EMPTY_GUID, encodeURIComponent(playlistId)); + } + + /** + * Builds the single entry route of a playlist by replacing the empty Id placeholder with the selected playlist Id. + * + * A single track is already identified, so it does not need the server to resolve a scope. It uses the entry route, + * which reports the added entry back to the caller. + * @param {string} playlistId - The Id of the selected playlist. + * @returns {string} The route that appends one track to the playlist. + */ + function buildTrackAddUrl(playlistId) { + const configuration = getConfiguration(); + const template = configuration ? configuration.addPlaylistEntryUrl : ''; + if (typeof template !== 'string' || template.length === 0) + return ''; + return template.replace(EMPTY_GUID, encodeURIComponent(playlistId)); + } + + /** + * Opens the playlist picker for a library, artist or album scope, or for one track, and appends it to the selected playlist. + * + * One picker serves every caller. It is created on demand and removed on close, so no hidden dialog stays in the + * layout, and the element that opened it gets the keyboard focus back. The playlist list is loaded only when the + * dialog opens, so a page that never uses the action does not make a request. + * @param {Object} scope - The scope to add. It carries libraryId, and optionally artistId, albumId, trackId and title. + * @returns {Promise} A promise that completes when the picker has opened. + */ + async function showAddScopeDialogAsync(scope) { + const configuration = getConfiguration(); + // Without the layout configuration there is no route to post to, and without a library there is no scope to + // resolve. The player can also call this module, so the check must not assume a page with playlist menus. + if (!configuration || !scope || !scope.libraryId || typeof document === 'undefined') + return; + // A second picker would compete for Escape and focus, and the user could add to two different playlists. + if (activePicker) + activePicker.close(); + + const strings = getStrings(); + const placeholder = strings.selectPlaylist || 'Select a playlist'; + // The caller's label is used for the title and the button, so the dialog wording matches the page it was opened + // from instead of always saying "Add to playlist". + const addLabel = scope.addToPlaylistLabel || 'Add to playlist'; + const pickerId = `playlist-picker-${++pickerSequence}`; + // Remember the trigger before the dialog takes focus, so closing it, including with Escape, returns the user to + // the control they used. The caller may pass the element explicitly because a menu item can be re-rendered. + const previousFocus = scope.returnFocus && scope.returnFocus.isConnected ? scope.returnFocus : document.activeElement; + + const overlay = document.createElement('div'); + overlay.className = 'playlist-picker-overlay'; + overlay.addEventListener('click', event => { + // Only the backdrop closes the dialog. A click inside the content must not dismiss it while the user is + // choosing a playlist or reading an error. + if (event.target === overlay) + close(); + }); + + const dialog = document.createElement('div'); + dialog.className = 'dialog'; + dialog.setAttribute('role', 'dialog'); + dialog.setAttribute('aria-modal', 'true'); + dialog.setAttribute('aria-labelledby', `${pickerId}-title`); + overlay.appendChild(dialog); + + const content = document.createElement('div'); + content.className = 'dialog-content'; + dialog.appendChild(content); + + const header = document.createElement('div'); + header.className = 'dialog-header'; + const title = document.createElement('h2'); + title.id = `${pickerId}-title`; + title.textContent = addLabel; + header.appendChild(title); + content.appendChild(header); + + const body = document.createElement('div'); + body.className = 'playlist-picker-body'; + content.appendChild(body); + + if (scope.title) { + // The same dialog is opened from a library, an artist, an album and a track menu. Showing the title tells the + // user what the action will add before they choose the playlist. + const scopeLabel = document.createElement('p'); + scopeLabel.className = 'playlist-picker-scope'; + scopeLabel.textContent = scope.title; + scopeLabel.title = scope.title; + body.appendChild(scopeLabel); + } + + const combobox = createCombobox(`${pickerId}-combobox`, placeholder); + body.appendChild(combobox.root); + + const emptyMessage = document.createElement('p'); + emptyMessage.className = 'playlist-picker-empty hidden'; + emptyMessage.textContent = strings.noPlaylists || ''; + if (configuration.createPlaylistUrl) { + const createLink = document.createElement('a'); + createLink.className = 'nav-link'; + createLink.href = configuration.createPlaylistUrl; + createLink.textContent = strings.createPlaylist || ''; + // The link navigates to the dedicated create page, so the dialog is closed first. Leaving the overlay in the + // page during the in-place navigation would cover the new page. + createLink.addEventListener('click', () => close()); + emptyMessage.appendChild(document.createTextNode(' ')); + emptyMessage.appendChild(createLink); + } + body.appendChild(emptyMessage); + + const buttons = document.createElement('div'); + buttons.className = 'dialog-buttons'; + content.appendChild(buttons); + + const cancelButton = document.createElement('button'); + cancelButton.type = 'button'; + cancelButton.className = 'dialog-button abort-button'; + cancelButton.textContent = (typeof jsLocalizedDialogs !== 'undefined' && jsLocalizedDialogs.cancel) || 'Cancel'; + cancelButton.addEventListener('click', () => close()); + buttons.appendChild(cancelButton); + + const addButton = document.createElement('button'); + addButton.type = 'button'; + addButton.className = 'dialog-button confirm-button'; + addButton.textContent = addLabel; + // Nothing can be added until the playlist request has returned and the user has made a choice. + addButton.disabled = true; + buttons.appendChild(addButton); + + const keyHandler = event => { + // Escape is the standard way to dismiss a modal. The listener is registered on the document, so close removes it. + if (event.key === 'Escape') + close(); + }; + + /** Closes the picker, removes its global listener and returns the focus to the element that opened it. */ + const close = () => { + // The dialog may already have been closed by a successful add, a backdrop click or another picker. Removing + // an already removed overlay and restoring focus twice would be harmless but noisy, so stop here. + if (!document.body.contains(overlay)) + return; + // The key listener is global, so it must be removed with the dialog; otherwise Escape would keep invoking a + // close function that no longer has a dialog to close. + document.removeEventListener('keydown', keyHandler); + overlay.remove(); + if (activePicker && activePicker.overlay === overlay) + activePicker = null; + if (previousFocus && typeof previousFocus.focus === 'function' && previousFocus.isConnected) + previousFocus.focus(); + }; + + activePicker = { close, overlay }; + document.addEventListener('keydown', keyHandler); + document.body.appendChild(overlay); + // Loading starts immediately, so the toggle stays disabled until the choices arrive; opening it earlier would + // show the placeholder as if it were a selectable playlist. + combobox.toggle.disabled = true; + + /** Fetches the playlists of the user and fills the picker, or shows the empty state and disables the action. */ + const loadPlaylistsAsync = async () => { + const playlists = await callApiGetAsync(configuration.getPlaylistsUrl); + // The dialog may have been closed while the request was in flight. Touching its removed DOM would throw or + // resurrect a stale overlay. + if (!document.body.contains(overlay)) + return; + if (!Array.isArray(playlists)) { + // The API helper returns null on a failed request. An empty, unusable dialog is worse than closing it + // and reporting the failure. + close(); + showNotification(strings.tracksAddFailed, true); + return; + } + if (playlists.length === 0) { + // There is nothing to choose. Disable the action and show the link that creates the first playlist, + // instead of letting the user press Add and receive an error. + combobox.selected.textContent = strings.noPlaylists || placeholder; + combobox.selected.setAttribute('data-value', ''); + emptyMessage.classList.remove('hidden'); + combobox.toggle.disabled = true; + addButton.disabled = true; + return; + } + fillPlaylists(combobox, playlists, placeholder); + combobox.toggle.disabled = false; + addButton.disabled = false; + // Move the keyboard focus into the dialog once it has content, so a keyboard user is not left on the trigger + // behind the modal. + addButton.focus(); + }; + + /** + * Adds the chosen scope or track to the selected playlist, then closes the picker and announces the update. + * The two routes differ because a single track is already identified, while a scope is resolved on the server. + */ + addButton.addEventListener('click', async () => { + const playlistId = combobox.selected.getAttribute('data-value') || ''; + if (!playlistId) { + // The placeholder row is present in the markup but carries an empty value, so it means no selection. + showNotification(strings.selectPlaylist, true); + return; + } + // The request may be slow. Disabling both controls prevents a second click from appending the same content + // twice, and makes the busy state visible. + addButton.disabled = true; + combobox.toggle.disabled = true; + try { + // A single track is already identified and uses the cheaper entry route. Everything else is a scope + // that the server resolves into its ordered tracks, so the browser never has to enumerate a library. + const isTrack = typeof scope.trackId === 'string' && scope.trackId.length > 0; + const addUrl = isTrack ? buildTrackAddUrl(playlistId) : buildScopeAddUrl(playlistId); + if (!addUrl) { + // The layout may not have rendered the route. Fail visibly instead of posting to an empty URL. + showNotification(strings.tracksAddFailed, true); + return; + } + const result = await callApiPostAsync(addUrl, isTrack + ? { trackId: scope.trackId } + : { + libraryId: scope.libraryId, + // Empty artist and album values mean "the whole scope"; sending them as null keeps the request + // shape explicit and avoids sending empty strings that the server would have to normalize. + artistId: scope.artistId || null, + albumId: scope.albumId || null + }); + if (!result) { + // The API helper already reported the failure; do not dispatch an update event for an add that did + // not happen. + showNotification(strings.tracksAddFailed, true); + return; + } + if (isTrack && !result.entry) { + // The single-entry response must contain the entry it added. A missing entry means the server did + // not append it, so this is a failure even if the HTTP call succeeded. + showNotification(strings.tracksAddFailed, true); + return; + } + if (!isTrack && result.addedCount === 0) { + // The scope resolved to no tracks, for example an empty album or an artist without releases. That + // is not a success and should not close the dialog silently. + showNotification(strings.noTracksToAdd, true); + return; + } + showNotification(strings.tracksAdded, false); + // Let an open playlist page refresh its window without coupling this module to that page. + document.dispatchEvent(new CustomEvent('lumina:playlist-updated', { detail: result })); + close(); + } catch (error) { + // callApiPostAsync normally resolves to null on failure; this catch is for unexpected errors, such as a + // rejected promise from a test double. Keep the dialog open so the user can retry. + console.error('Playlists: adding to a playlist failed.', error); + showNotification(strings.tracksAddFailed, true); + } finally { + // After a success the dialog is already removed, so only an open dialog is re-enabled. + if (document.body.contains(overlay)) { + addButton.disabled = false; + combobox.toggle.disabled = false; + } + } + }); + + loadPlaylistsAsync().catch(error => { + // A rejected request leaves the dialog unusable: there are no choices and no way to load them again. Close + // it and surface the failure instead of leaving an empty picker on screen. + console.error('Playlists: loading the playlists failed.', error); + if (document.body.contains(overlay)) { + close(); + showNotification(strings.tracksAddFailed, true); + } + }); + } + + window.LuminaPlaylists = { + showAddScopeDialogAsync + }; +})(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs index 408dc94b..1c4a3947 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumLiteRowFixture.cs @@ -45,15 +45,13 @@ public class AlbumLiteRowFixture bool includeReleaseYear = true, bool includeReleaseTypes = true) { - return new AlbumLiteRow - { - Id = id ?? _faker.Random.Guid(), - Title = title ?? _faker.Music.Genre(), - TotalTracks = totalTracks ?? _faker.Random.Int(1, 30), - CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null, - ReleaseYear = includeReleaseYear ? (releaseYear ?? _faker.Random.Int(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR)) : null, - ReleaseTypes = includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(index => _faker.PickRandom())]) : null - }; + return new AlbumLiteRow( + id ?? _faker.Random.Guid(), + title ?? _faker.Music.Genre(), + totalTracks ?? _faker.Random.Int(1, 30), + includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null, + includeReleaseYear ? (releaseYear ?? _faker.Random.Int(MINIMUM_RELEASE_YEAR, MAXIMUM_RELEASE_YEAR)) : null, + includeReleaseTypes ? (releaseTypes ?? [.. Enumerable.Range(0, _faker.Random.Int(1, 3)).Select(index => _faker.PickRandom())]) : null); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs index 708c4ac0..4611dc09 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Artists/ArtistLiteRowFixture.cs @@ -31,12 +31,10 @@ public class ArtistLiteRowFixture string? coverPath = null, bool includeCoverPath = true) { - return new ArtistLiteRow - { - Id = id ?? _faker.Random.Guid(), - Name = name ?? _faker.Name.FullName(), - CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null - }; + return new ArtistLiteRow( + id ?? _faker.Random.Guid(), + name ?? _faker.Name.FullName(), + includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs index d942eac7..05b1687b 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackLiteRowFixture.cs @@ -35,14 +35,12 @@ public class TrackLiteRowFixture bool includeDiscNumber = true, int? durationInSeconds = null) { - return new TrackLiteRow - { - Id = id ?? _faker.Random.Guid(), - Title = title ?? _faker.Lorem.Sentence(), - TrackNumber = trackNumber ?? _faker.Random.Int(1, 30), - DiscNumber = includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, - DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 600) - }; + return new TrackLiteRow( + id ?? _faker.Random.Guid(), + title ?? _faker.Lorem.Sentence(), + trackNumber ?? _faker.Random.Int(1, 30), + includeDiscNumber ? (discNumber ?? _faker.Random.Int(1, 3)) : null, + durationInSeconds ?? _faker.Random.Int(1, 600)); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs index 67048e20..d5db5b88 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookLiteRowFixture.cs @@ -31,13 +31,11 @@ public class BookLiteRowFixture int? releaseYear = null, string? coverPath = null) { - return new BookLiteRow - { - Id = id ?? _faker.Random.Guid(), - Title = title ?? _faker.Lorem.Sentence(), - ReleaseYear = releaseYear, - CoverPath = coverPath - }; + return new BookLiteRow( + id ?? _faker.Random.Guid(), + title ?? _faker.Lorem.Sentence(), + releaseYear, + coverPath); } /// diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntityFixture.cs new file mode 100644 index 00000000..f800675f --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntityFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist. + /// Optional. The Id of the user that owns the playlist. + /// Optional. The name of the playlist. + /// Whether the description should be populated. + /// Optional. The description of the playlist. + /// Optional. The kind of media the playlist holds. + /// Optional. The ordered entries of the playlist. + /// Optional. The number of entries the playlist holds. + /// Optional. The concurrency token of the playlist. + /// Optional. The time and date when the playlist was created. + /// Optional. The Id of the user that created the playlist. + /// Whether the update time should be populated. + /// Optional. The time and date when the playlist was updated. + /// Optional. The Id of the user that updated the playlist. + /// The created playlist entity. + public PlaylistEntity Create( + Guid? id = null, + Guid? userId = null, + string? name = null, + bool includeDescription = true, + string? description = null, + PlaylistType? type = null, + IEnumerable? entries = null, + int? entryCount = null, + long? version = null, + DateTime? createdOnUtc = null, + Guid? createdBy = null, + bool includeUpdatedOnUtc = false, + DateTime? updatedOnUtc = null, + Guid? updatedBy = null) + { + Guid playlistId = id ?? Guid.NewGuid(); + List resolvedEntries = entries is null ? [] : [.. entries]; + + return new Faker() + .CustomInstantiator(f => new PlaylistEntity + { + Id = playlistId, + UserId = userId ?? f.Random.Guid(), + Name = name ?? f.Lorem.Sentence(3), + Description = includeDescription ? (description ?? f.Lorem.Sentence()) : null, + Type = type ?? f.PickRandom(), + Entries = resolvedEntries, + EntryCount = entryCount ?? resolvedEntries.Count, + Version = version ?? f.Random.Long(0, 1_000L), + CreatedOnUtc = createdOnUtc ?? f.Date.Past(), + CreatedBy = createdBy ?? f.Random.Guid(), + UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? f.Date.Recent()) : null, + UpdatedBy = includeUpdatedOnUtc ? (updatedBy ?? f.Random.Guid()) : null + }) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// Optional. The Id of the user that owns the created playlists. + /// List of configured instances. + public List CreateMany(int count = 3, Guid? userId = null) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(userId: userId))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntryEntityFixture.cs new file mode 100644 index 00000000..0f8e05a5 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Playlists/PlaylistEntryEntityFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the entry. + /// Optional. The Id of the playlist the entry belongs to. + /// Optional. The Id of the referenced media item. + /// Optional. The kind of the referenced media item. + /// Optional. The sparse order key of the entry. + /// Optional. The time and date when the entry was created. + /// Optional. The Id of the user that created the entry. + /// Whether the update time should be populated. + /// Optional. The time and date when the entry was updated. + /// Optional. The Id of the user that updated the entry. + /// The created playlist entry entity. + public PlaylistEntryEntity Create( + Guid? id = null, + Guid? playlistId = null, + Guid? mediaItemId = null, + PlaylistMediaItemType? mediaItemType = null, + long? position = null, + DateTime? createdOnUtc = null, + Guid? createdBy = null, + bool includeUpdatedOnUtc = false, + DateTime? updatedOnUtc = null, + Guid? updatedBy = null) + { + return new Faker() + .CustomInstantiator(f => new PlaylistEntryEntity + { + Id = id ?? f.Random.Guid(), + PlaylistId = playlistId ?? f.Random.Guid(), + MediaItemId = mediaItemId ?? f.Random.Guid(), + MediaItemType = mediaItemType ?? f.PickRandom(), + Position = position ?? f.Random.Long(0, 1_000_000_000L), + CreatedOnUtc = createdOnUtc ?? f.Date.Past(), + CreatedBy = createdBy ?? f.Random.Guid(), + UpdatedOnUtc = includeUpdatedOnUtc ? (updatedOnUtc ?? f.Date.Recent()) : null, + UpdatedBy = includeUpdatedOnUtc ? (updatedBy ?? f.Random.Guid()) : null + }) + .Generate(); + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs index 86f9c283..ef4eb16a 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs @@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Common.Dapper; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; @@ -49,6 +50,8 @@ public class LibraryScanSnapshotRepositoryTests : IDisposable _anchorConnection.Open(); _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connectionString).Options); _context.Database.EnsureCreated(); + // The production composition root registers this handler, so the integration tests must exercise the same Guid representation. + DapperTypeHandlers.Register(); _sut = new LibraryScanSnapshotRepository(_context); } diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs new file mode 100644 index 00000000..6b9479c4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/Playlists/PlaylistRepositoryTests.cs @@ -0,0 +1,485 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.Repositories.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.DataAccess.IntegrationTests.Core.Repositories.Playlists; + +/// +/// Contains integration tests for the class, exercising it against a real SQLite database. +/// +[ExcludeFromCodeCoverage] +public class PlaylistRepositoryTests +{ + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + + [Fact] + public async Task UpdateAsync_WhenNoEditableValueChanged_ShouldNotModifyTheStoredPlaylist() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-update-noop-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + PlaylistRepository sut = new(context); + context.Users.Add(_userEntityFixture.Create(id: userId)); + PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 7); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + long storedVersion = playlist.Version; + // A detached copy is the same shape the command mapping produces for an edit, so this is a real no-op round-trip instead of an object built only to satisfy the repository signature. + PlaylistEntity incoming = await context.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlist.Id); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + PlaylistEntity storedPlaylist = await context.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Equal(storedVersion, storedPlaylist.Version); + Assert.Equal(7, storedPlaylist.EntryCount); + Assert.Null(storedPlaylist.UpdatedOnUtc); + } + + [Fact] + public async Task UpdateAsync_WhenOnlyTheNameChanged_ShouldIncrementTheVersionAndPreserveTheEntryCount() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-update-name-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + Guid userId = Guid.NewGuid(); + DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow); + PlaylistRepository sut = new(context); + context.Users.Add(_userEntityFixture.Create(id: userId)); + PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 7); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + long storedVersion = playlist.Version; + // The mapped edit path does not load the entries, so its entry count is zero. The test proves the repository preserves the stored count instead of copying that zero onto the playlist. + PlaylistEntity incoming = _playlistEntityFixture.Create( + id: playlist.Id, + userId: userId, + name: "Renamed playlist", + type: PlaylistType.Music, + entryCount: 0); + + // Act + Result result = await sut.UpdateAsync(incoming, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + PlaylistEntity storedPlaylist = await context.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Equal("Renamed playlist", storedPlaylist.Name); + Assert.Equal(storedVersion + 1, storedPlaylist.Version); + Assert.Equal(7, storedPlaylist.EntryCount); + Assert.Equal(utcNow, storedPlaylist.UpdatedOnUtc); + } + + [Fact] + public async Task GetAllForUserAsync_WhenTheUserHasPlaylists_ShouldReturnTheirStoredEntryCounts() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-list-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + PlaylistEntity firstPlaylist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 7); + PlaylistEntity secondPlaylist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0); + context.Playlists.AddRange(firstPlaylist, secondPlaylist); + await context.SaveChangesAsync(); + + // Act + Result> result = await sut.GetAllForUserAsync(userId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Contains(result.Value, playlist => playlist.Id == firstPlaylist.Id && playlist.EntryCount == 7); + Assert.Contains(result.Value, playlist => playlist.Id == secondPlaylist.Id && playlist.EntryCount == 0); + } + + [Fact] + public async Task AddScopeEntriesAsync_WhenTheWholeLibraryIsAppended_ShouldInsertCatalogueOrderAndUpdateTheEntryCount() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-scope-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid libraryId = Guid.NewGuid(); + List orderedTracks = await SeedCatalogueAsync(context, libraryId); + PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + DateTime updatedOnUtc = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + // Act + Result result = await sut.AddScopeEntriesAsync( + playlist.Id, + userId, + libraryId, + artistId: null, + albumId: null, + PlaylistMediaItemType.MusicTrack, + updatedOnUtc, + CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(orderedTracks.Count, result.Value.AddedCount); + List storedEntries = await context.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlist.Id) + .OrderBy(entry => entry.Position) + .ToListAsync(); + Assert.Equal(orderedTracks.Select(track => track.Id), storedEntries.Select(entry => entry.MediaItemId)); + Assert.All(storedEntries, entry => Assert.NotEqual(Guid.Empty, entry.Id)); + // The generated entry Ids must be stored in the same text form the provider uses, so the appended entry can still be read back by + // its Id through a normal Entity Framework parameter. It is the last entry, so its display position comes from the stored count. + Result storedEntryResult = await sut.GetAppendedEntryDetailsForUserAsync(playlist.Id, userId, storedEntries[^1].Id, CancellationToken.None); + Assert.False(storedEntryResult.IsFailure); + Assert.NotNull(storedEntryResult.Value); + Assert.Equal(orderedTracks.Count - 1, storedEntryResult.Value!.DisplayPosition); + Assert.NotNull(storedEntryResult.Value.Display); + PlaylistEntity storedPlaylist = await context.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Equal(orderedTracks.Count, storedPlaylist.EntryCount); + Assert.Equal(1L, storedPlaylist.Version); + Assert.Equal(updatedOnUtc, storedPlaylist.UpdatedOnUtc); + // A window read reports the stored count of the whole playlist while materializing only the requested window. + Result detailsResult = await sut.GetDetailsForUserAsync(playlist.Id, userId, offset: 0, limit: 2, CancellationToken.None); + Assert.False(detailsResult.IsFailure); + Assert.NotNull(detailsResult.Value); + Assert.Equal(orderedTracks.Count, detailsResult.Value!.Playlist.EntryCount); + Assert.Equal(2, detailsResult.Value.Entries.Count); + } + + [Fact] + public async Task AddScopeEntriesAsync_WhenAnAlbumIsSpecified_ShouldAppendOnlyThatAlbum() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-scope-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid libraryId = Guid.NewGuid(); + List orderedTracks = await SeedCatalogueAsync(context, libraryId); + AlbumEntity album = await context.Albums.FirstAsync(candidate => candidate.Id == orderedTracks[0].AlbumId); + PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.AddScopeEntriesAsync( + playlist.Id, + userId, + libraryId, + artistId: album.ArtistId, + albumId: album.Id, + PlaylistMediaItemType.MusicTrack, + DateTime.UtcNow, + CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + List storedMediaItemIds = await context.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlist.Id) + .OrderBy(entry => entry.Position) + .Select(entry => entry.MediaItemId) + .ToListAsync(); + Assert.Equal( + orderedTracks.Where(track => track.AlbumId == album.Id).Select(track => track.Id), + storedMediaItemIds); + } + + [Fact] + public async Task AddEntriesAsync_WhenALaterBatchFails_ShouldLeaveNoPrefixWhenTheAmbientTransactionIsRolledBack() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-batch-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + PlaylistEntity playlist = _playlistEntityFixture.Create(userId: userId, type: PlaylistType.Music, entryCount: 0, version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + List mediaItemIds = [.. Enumerable.Range(0, 501).Select(_ => Guid.NewGuid())]; + List entryIds = [.. mediaItemIds.Select(_ => Guid.NewGuid())]; + // The duplicate in the second batch violates the primary key after the first batch was already inserted. + entryIds[500] = entryIds[0]; + + // Act + // This is the transaction the request middleware owns in production. The repository must not take a decision about it: the middleware rolls it back once the response is known to be unsuccessful. + using IDbContextTransaction ambientTransaction = await context.Database.BeginTransactionAsync(); + // A primary key violation is not one of the mapped persistence conflicts, so it takes the generic failure path. + await Assert.ThrowsAsync(() => sut.AddEntriesAsync( + playlist.Id, + userId, + mediaItemIds, + PlaylistMediaItemType.MusicTrack, + entryIds, + DateTime.UtcNow, + CancellationToken.None)); + + // The middleware rolls the request transaction back after a failed response. + await ambientTransaction.RollbackAsync(); + + // Assert + // The ambient transaction has been rolled back, so another connection can read the database and sees no partial prefix. + using LuminaDbContext verificationContext = CreateContext(anchorConnection); + Assert.Equal(0, await verificationContext.PlaylistEntries.CountAsync(entry => entry.PlaylistId == playlist.Id)); + PlaylistEntity storedPlaylist = await verificationContext.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Equal(0, storedPlaylist.EntryCount); + Assert.Equal(0L, storedPlaylist.Version); + } + + [Fact] + public async Task DeleteByIdAsync_WhenThePlaylistExists_ShouldRemoveThePlaylistAndItsEntries() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-delete-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid playlistId = Guid.NewGuid(); + PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 1_000_000_000L); + PlaylistEntryEntity secondEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 2_000_000_000L); + PlaylistEntity playlist = _playlistEntityFixture.Create( + id: playlistId, + userId: userId, + type: PlaylistType.Music, + entries: [firstEntry, secondEntry], + entryCount: 2); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + // A real delete request starts with no tracked entries, so the database cascade is the path that has to remove them. + context.ChangeTracker.Clear(); + + // Act + Result result = await sut.DeleteByIdAsync(playlistId, CancellationToken.None); + await context.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(await context.Playlists.AsNoTracking().AnyAsync(candidate => candidate.Id == playlistId)); + Assert.False(await context.PlaylistEntries.AsNoTracking().AnyAsync(entry => entry.PlaylistId == playlistId)); + } + + [Fact] + public async Task DeleteByIdAsync_WhenThePlaylistDoesNotExist_ShouldReturnPlaylistNotFound() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-delete-missing-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + + // Act + Result result = await sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError); + } + + [Fact] + public async Task MoveEntryAsync_WhenMovingAnEntry_ShouldUpdateItsPositionWithoutChangingTheEntryCount() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-move-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid playlistId = Guid.NewGuid(); + PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 1_000_000_000L); + PlaylistEntryEntity secondEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 2_000_000_000L); + PlaylistEntryEntity thirdEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 3_000_000_000L); + PlaylistEntity playlist = _playlistEntityFixture.Create( + id: playlistId, + userId: userId, + type: PlaylistType.Music, + entries: [firstEntry, secondEntry, thirdEntry], + entryCount: 3, + version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.MoveEntryAsync(playlistId, userId, thirdEntry.Id, targetPosition: 0, DateTime.UtcNow, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + List orderedMediaItemIds = await context.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId) + .OrderBy(entry => entry.Position) + .Select(entry => entry.MediaItemId) + .ToListAsync(); + Assert.Equal([thirdEntry.MediaItemId, firstEntry.MediaItemId, secondEntry.MediaItemId], orderedMediaItemIds); + PlaylistEntity storedPlaylist = await context.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(3, storedPlaylist.EntryCount); + Assert.Equal(1L, storedPlaylist.Version); + } + + [Fact] + public async Task RemoveEntryAsync_WhenTheEntryExists_ShouldDecrementTheStoredEntryCount() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-playlistrepo-remove-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext context = CreateContext(anchorConnection); + PlaylistRepository sut = new(context); + Guid userId = Guid.NewGuid(); + context.Users.Add(_userEntityFixture.Create(id: userId)); + Guid playlistId = Guid.NewGuid(); + PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 1_000_000_000L); + PlaylistEntryEntity secondEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 2_000_000_000L); + PlaylistEntity playlist = _playlistEntityFixture.Create( + id: playlistId, + userId: userId, + type: PlaylistType.Music, + entries: [firstEntry, secondEntry], + entryCount: 2, + version: 0); + context.Playlists.Add(playlist); + await context.SaveChangesAsync(); + + // Act + Result result = await sut.RemoveEntryAsync(playlistId, userId, firstEntry.Id, DateTime.UtcNow, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + PlaylistEntity storedPlaylist = await context.Playlists + .AsNoTracking() + .FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(1, storedPlaylist.EntryCount); + Assert.Equal(1L, storedPlaylist.Version); + Assert.False(await context.PlaylistEntries.AsNoTracking().AnyAsync(entry => entry.Id == firstEntry.Id)); + } + + /// + /// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The Id of the user reported as the current user. + /// The current UTC time reported by the time provider. + /// The created context. + private static LuminaDbContext CreateAuditedContext(SqliteConnection anchorConnection, Guid userId, DateTime utcNow) + { + ICurrentUserService currentUserService = Substitute.For(); + currentUserService.UserId.Returns(userId); + IDateTimeProvider dateTimeProvider = Substitute.For(); + dateTimeProvider.UtcNow.Returns(utcNow); + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .AddInterceptors(new UpdateAuditableEntitiesInterceptor(currentUserService, dateTimeProvider)) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Creates a real SQLite backed context without the auditing interceptor. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The created context. + private static LuminaDbContext CreateContext(SqliteConnection anchorConnection) + { + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Seeds two artists and three albums with four tracks in total, and returns the tracks in the order a playlist must receive them. + /// + /// The context to seed. + /// The Id of the library the catalogue belongs to. + /// The tracks in artist, album, disc and track order. + private async Task> SeedCatalogueAsync(LuminaDbContext context, Guid libraryId) + { + ArtistEntity betaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Beta Artist", includeAlbums: false, includeContributors: false); + ArtistEntity alphaArtist = _artistEntityFixture.Create(libraryId: libraryId, name: "Alpha Artist", includeAlbums: false, includeContributors: false); + context.Artists.AddRange(betaArtist, alphaArtist); + await context.SaveChangesAsync(); + + AlbumEntity betaAlbum = _albumEntityFixture.Create(artistId: betaArtist.Id, libraryId: libraryId, title: "Only Album", includeTracks: false, includeMetadata: false); + AlbumEntity alphaZetaAlbum = _albumEntityFixture.Create(artistId: alphaArtist.Id, libraryId: libraryId, title: "Zeta", includeTracks: false, includeMetadata: false); + AlbumEntity alphaAlphaAlbum = _albumEntityFixture.Create(artistId: alphaArtist.Id, libraryId: libraryId, title: "Alpha", includeTracks: false, includeMetadata: false); + context.Albums.AddRange(betaAlbum, alphaZetaAlbum, alphaAlphaAlbum); + await context.SaveChangesAsync(); + + TrackEntity betaTrack = _trackEntityFixture.Create(albumId: betaAlbum.Id, libraryId: libraryId, title: "Beta One", trackNumber: 1, includeMetadata: false); + TrackEntity alphaZetaTrack = _trackEntityFixture.Create(albumId: alphaZetaAlbum.Id, libraryId: libraryId, title: "Alpha Zeta One", trackNumber: 1, includeMetadata: false); + TrackEntity alphaAlphaSecondTrack = _trackEntityFixture.Create(albumId: alphaAlphaAlbum.Id, libraryId: libraryId, title: "Alpha Alpha Two", trackNumber: 2, includeMetadata: false); + TrackEntity alphaAlphaFirstTrack = _trackEntityFixture.Create(albumId: alphaAlphaAlbum.Id, libraryId: libraryId, title: "Alpha Alpha One", trackNumber: 1, includeMetadata: false); + // The fixture randomizes the disc number, so it is pinned here to make the track order of the album deterministic. + betaTrack.DiscNumber = 1; + alphaZetaTrack.DiscNumber = 1; + alphaAlphaSecondTrack.DiscNumber = 1; + alphaAlphaFirstTrack.DiscNumber = 1; + // The tracks are deliberately inserted out of catalogue order, so the test proves that the database produces the playlist order. + context.Tracks.AddRange(betaTrack, alphaZetaTrack, alphaAlphaSecondTrack, alphaAlphaFirstTrack); + await context.SaveChangesAsync(); + + return [alphaAlphaFirstTrack, alphaAlphaSecondTrack, alphaZetaTrack, betaTrack]; + } +} diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs index d9f4c2a8..6da1c5d9 100644 --- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs @@ -48,7 +48,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(63, tableNames.Length); + Assert.Equal(65, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -109,6 +109,8 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("MusicArtwork", tableNames); Assert.Contains("MusicLibraryScanItemMetadata", tableNames); Assert.Contains("MusicPlayRecords", tableNames); + Assert.Contains("Playlists", tableNames); + Assert.Contains("PlaylistEntries", tableNames); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs index 605d437e..94279eb9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Dapper/SqliteGuidTypeHandlerTests.cs @@ -25,7 +25,7 @@ public class SqliteGuidTypeHandlerTests } [Fact] - public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsTextRepresentation() + public void SetValue_WhenCalled_ShouldStoreTheGuidAsItsUpperCaseTextRepresentation() { // Arrange IDbDataParameter parameter = Substitute.For(); @@ -35,7 +35,7 @@ public class SqliteGuidTypeHandlerTests _sut.SetValue(parameter, guid); // Assert - Assert.Equal(guid.ToString(), (string?)parameter.Value); + Assert.Equal(guid.ToString().ToUpperInvariant(), (string?)parameter.Value); } [Fact] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs new file mode 100644 index 00000000..446f3f93 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistTests +{ + [Fact] + public void Delete_WhenCalled_ShouldMarkThePlaylistAsDeletedAndRaiseOneEvent() + { + // Arrange + Result createResult = Playlist.Create( + UserId.Create(Guid.NewGuid()), + "Playlist", + Optional.None(), + PlaylistType.Music); + Assert.False(createResult.IsFailure); + Playlist playlist = createResult.Value; + Assert.False(playlist.IsDeleted); + + // Act + Result result = playlist.Delete(); + List domainEvents = playlist.GetDomainEvents(); + + // Assert + Assert.False(result.IsFailure); + Assert.True(playlist.IsDeleted); + Assert.Single(domainEvents); + Assert.IsType(domainEvents[0]); + } + + [Fact] + public void Delete_WhenCalledAgain_ShouldNotRaiseAnotherEvent() + { + // Arrange + Result createResult = Playlist.Create( + UserId.Create(Guid.NewGuid()), + "Playlist", + Optional.None(), + PlaylistType.Music); + Assert.False(createResult.IsFailure); + Playlist playlist = createResult.Value; + playlist.Delete(); + + // Act + Result result = playlist.Delete(); + List domainEvents = playlist.GetDomainEvents(); + + // Assert + Assert.False(result.IsFailure); + Assert.True(playlist.IsDeleted); + Assert.Single(domainEvents); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs index 022605c9..feb31009 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; @@ -29,7 +28,6 @@ public class LibraryOwnershipPolicyTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IUserRepository _mockUserRepository; - private readonly ILibraryRepository _mockLibraryRepository; private readonly LibraryOwnershipPolicy _sut; private readonly AuthorizationServiceFixture _authorizationServiceFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); @@ -42,9 +40,7 @@ public class LibraryOwnershipPolicyTests _mockUnitOfWork = Substitute.For(); _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); _mockUserRepository = Substitute.For(); - _mockLibraryRepository = Substitute.For(); _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); - _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); _sut = new LibraryOwnershipPolicy(_mockUnitOfWork); } @@ -61,7 +57,6 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -78,7 +73,6 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -95,7 +89,6 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); } [Fact] @@ -116,45 +109,6 @@ public class LibraryOwnershipPolicyTests // Assert Assert.True(result); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()); - } - - [Fact] - public async Task EvaluateAsync_WhenLibraryDoesNotExist_ShouldReturnFalse() - { - // Arrange - Guid userId = Guid.NewGuid(); - UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); - LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) - .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) - .Returns(Result.Success(null)); - - // Act - bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None); - - // Assert - Assert.False(result); - } - - [Fact] - public async Task EvaluateAsync_WhenGetLibraryFails_ShouldReturnFalse() - { - // Arrange - Guid userId = Guid.NewGuid(); - UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); - LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); - _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) - .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) - .Returns(Error.Failure("Database.Error", "Failed to retrieve library")); - - // Act - bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None); - - // Assert - Assert.False(result); } [Fact] @@ -164,11 +118,10 @@ public class LibraryOwnershipPolicyTests Guid userId = Guid.NewGuid(); UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryEntity library = _libraryEntityFixture.Create(userId: userId); + regularUser.Libraries.Add(library); LibraryOwnershipPolicyContext context = new(library.Id); _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) - .Returns(Result.From(library)); // Act bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None); @@ -187,8 +140,6 @@ public class LibraryOwnershipPolicyTests LibraryOwnershipPolicyContext context = new(library.Id); _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) .Returns(Result.From(regularUser)); - _mockLibraryRepository.GetByIdAsync(context.LibraryId, cancellationToken: Arg.Any()) - .Returns(Result.From(library)); // Act bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None); @@ -196,4 +147,26 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); } + + [Fact] + public async Task EvaluateAsync_WhenMultipleLibrariesAreEvaluated_ShouldReadTheUserOnlyOnce() + { + // Arrange + Guid userId = Guid.NewGuid(); + UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); + LibraryEntity ownedLibrary = _libraryEntityFixture.Create(userId: userId); + regularUser.Libraries.Add(ownedLibrary); + _mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any()) + .Returns(Result.From(regularUser)); + + // Act + // The policy is scoped to one request, so both library checks in that scope must share a single user read. + bool canAccessOwnedLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(ownedLibrary.Id), CancellationToken.None); + bool canAccessOtherLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(Guid.NewGuid()), CancellationToken.None); + + // Assert + Assert.True(canAccessOwnedLibrary); + Assert.False(canAccessOtherLibrary); + await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs index a0a644be..81a6581a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/EventualConsistencyMiddlewareTests.cs @@ -1,10 +1,22 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Events; using Lumina.Presentation.Api.Common.Http; using Lumina.Presentation.Api.Common.Middlewares; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NSubstitute; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; using System.Threading.Tasks; #endregion @@ -52,4 +64,186 @@ public class EventualConsistencyMiddlewareTests // Assert Assert.True(_nextInvoked); } + + [Fact] + public async Task InvokeAsync_WhenTheClientAbortsAfterASuccessfulOperation_ShouldStillCommitTheTransaction() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-abort-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext dbContext = CreateContext(anchorConnection); + using UnitOfWork unitOfWork = new(dbContext); + await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);"); + CapturingHttpResponseFeature responseFeature = new(); + DefaultHttpContext httpContext = new(); + httpContext.Features.Set(responseFeature); + httpContext.Request.Path = "/api/v1/probe"; + httpContext.Response.StatusCode = StatusCodes.Status200OK; + using CancellationTokenSource cancellationTokenSource = new(); + httpContext.RequestAborted = cancellationTokenSource.Token; + ILogger mockLogger = Substitute.For>(); + EventualConsistencyMiddleware sut = new( + async requestContext => + { + await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);"); + // The abort happens after the operation has completed, which is exactly when the response token can already be cancelled as the completion callback runs. + cancellationTokenSource.Cancel(); + }, + mockLogger); + IDomainEventPublisher mockPublisher = Substitute.For(); + IDomainEventsQueue mockQueue = Substitute.For(); + + // Act + await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue); + await responseFeature.InvokeCompletedCallbacksAsync(); + + // Assert + using LuminaDbContext verificationContext = CreateContext(anchorConnection); + int committedCount = await verificationContext.Database + .SqlQueryRaw("SELECT COUNT(*) AS \"Value\" FROM CommitProbe") + .SingleAsync(); + Assert.Equal(1, committedCount); + } + + [Fact] + public async Task InvokeAsync_WhenTheResponseIsNotSuccessful_ShouldRollBackTheTransactionAndTheEvents() + { + // Arrange + using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-eventual-consistency-rollback-{Guid.NewGuid()};Mode=Memory;Cache=Shared"); + anchorConnection.Open(); + using LuminaDbContext dbContext = CreateContext(anchorConnection); + using UnitOfWork unitOfWork = new(dbContext); + await dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE CommitProbe (Id INTEGER NOT NULL PRIMARY KEY);"); + CapturingHttpResponseFeature responseFeature = new(); + DefaultHttpContext httpContext = new(); + httpContext.Features.Set(responseFeature); + httpContext.Request.Path = "/api/v1/probe"; + ILogger mockLogger = Substitute.For>(); + EventualConsistencyMiddleware sut = new( + async requestContext => + { + await dbContext.Database.ExecuteSqlRawAsync("INSERT INTO CommitProbe (Id) VALUES (1);"); + // A client abort is reported by the exception handling middleware as a non-success status, even though the request reached the database. + requestContext.Response.StatusCode = StatusCodes.Status499ClientClosedRequest; + }, + mockLogger); + IDomainEventPublisher mockPublisher = Substitute.For(); + IDomainEventsQueue mockQueue = Substitute.For(); + + // Act + await sut.InvokeAsync(httpContext, mockPublisher, unitOfWork, mockQueue); + await responseFeature.InvokeCompletedCallbacksAsync(); + + // Assert + using LuminaDbContext verificationContext = CreateContext(anchorConnection); + int committedCount = await verificationContext.Database + .SqlQueryRaw("SELECT COUNT(*) AS \"Value\" FROM CommitProbe") + .SingleAsync(); + Assert.Equal(0, committedCount); + await mockPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task InvokeAsync_WhenTheCommitFails_ShouldRollBackTheTransactionAndLogTheFailure() + { + // Arrange + CapturingHttpResponseFeature responseFeature = new(); + DefaultHttpContext httpContext = new(); + httpContext.Features.Set(responseFeature); + httpContext.Request.Path = "/api/v1/probe"; + httpContext.Response.StatusCode = StatusCodes.Status200OK; + ILogger mockLogger = Substitute.For>(); + EventualConsistencyMiddleware sut = new(_ => Task.CompletedTask, mockLogger); + IUnitOfWork mockUnitOfWork = Substitute.For(); + mockUnitOfWork + .CommitTransactionAsync(Arg.Any()) + .Returns(Task.FromException(new InvalidOperationException("commit failed"))); + IDomainEventPublisher mockPublisher = Substitute.For(); + IDomainEventsQueue mockQueue = Substitute.For(); + + // Act + await sut.InvokeAsync(httpContext, mockPublisher, mockUnitOfWork, mockQueue); + await responseFeature.InvokeCompletedCallbacksAsync(); + + // Assert + // The completion callback must never leave a transaction open after a failed commit, and it must never publish events that belong to a transaction that did not commit. + await mockUnitOfWork.Received(1).RollbackTransactionAsync(Arg.Any()); + await mockPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + } + + /// + /// Creates a context backed by the provided in-memory SQLite connection. + /// + /// The open in-memory SQLite connection that keeps the database alive for the duration of the test. + /// The created context. + private static LuminaDbContext CreateContext(SqliteConnection anchorConnection) + { + LuminaDbContext context = new(new DbContextOptionsBuilder() + .UseSqlite(anchorConnection.ConnectionString) + .Options); + context.Database.EnsureCreated(); + return context; + } + + /// + /// Response feature that captures the completed callbacks so a test can run them when the response ends. + /// + private sealed class CapturingHttpResponseFeature : IHttpResponseFeature + { + private readonly List> _completedCallbacks = []; + + /// + /// Gets or sets the HTTP status code of the response. + /// + public int StatusCode { get; set; } = StatusCodes.Status200OK; + + /// + /// Gets or sets the reason phrase of the response. + /// + public string? ReasonPhrase { get; set; } + + /// + /// Gets or sets the response headers. + /// + public IHeaderDictionary Headers { get; set; } = new HeaderDictionary(); + + /// + /// Gets or sets the response body stream. + /// + public Stream Body { get; set; } = Stream.Null; + + /// + /// Gets a value indicating whether the response has already started. + /// + public bool HasStarted => false; + + /// + /// Registers a callback to be invoked when the response is about to start. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnStarting(Func callback, object state) + { + } + + /// + /// Registers a callback to be invoked when the response has completed. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnCompleted(Func callback, object state) + { + _completedCallbacks.Add(() => callback(state)); + } + + /// + /// Invokes every callback that was registered through . + /// + /// A task representing the asynchronous operation. + public async Task InvokeCompletedCallbacksAsync() + { + foreach (Func callback in _completedCallbacks) + await callback(); + } + } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index afcbea42..a273e912 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -112,7 +112,7 @@ public class ExceptionHandlingMiddlewareTests } [Fact] - public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrow() + public async Task InvokeAsync_WhenNextThrowsOperationCanceledException_ShouldRethrowAndReportTheRequestAsAborted() { // Arrange DefaultHttpContext context = new() @@ -125,7 +125,8 @@ public class ExceptionHandlingMiddlewareTests await Assert.ThrowsAsync(() => _sut.InvokeAsync(context)); // Assert - Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); + // An aborted request is still reported as a non-success status, so the eventual consistency middleware rolls its writes back. + Assert.Equal(StatusCodes.Status499ClientClosedRequest, context.Response.StatusCode); Assert.Equal(0, context.Response.Body.Length); }