mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds playlist management and playback
This commit is contained in:
1 parent
009a0c8156
commit
9889c86c76
296 files changed
+18830
-367
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+24
-2
@@ -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.
|
||||
+14
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
+14
-32
@@ -9,35 +9,17 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A
|
||||
/// <summary>
|
||||
/// Lightweight read model of an album, containing only the fields needed to display the album in a card-based grid or a list.
|
||||
/// </summary>
|
||||
public sealed record AlbumLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the album.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the album.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of tracks of the release.
|
||||
/// </summary>
|
||||
public int TotalTracks { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the image representing the album, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the release year of the album (the re-release year, if available, or the original release year), if known.
|
||||
/// </summary>
|
||||
public int? ReleaseYear { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the set of types of the release.
|
||||
/// </summary>
|
||||
public List<MusicReleaseType>? ReleaseTypes { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the album.</param>
|
||||
/// <param name="Title">The title of the album.</param>
|
||||
/// <param name="TotalTracks">The number of tracks of the release.</param>
|
||||
/// <param name="CoverPath">The path of the image representing the album, if available.</param>
|
||||
/// <param name="ReleaseYear">The release year of the album (the re-release year, if available, or the original release year), if known.</param>
|
||||
/// <param name="ReleaseTypes">The set of types of the release.</param>
|
||||
public sealed record AlbumLiteRow(
|
||||
Guid Id,
|
||||
string Title,
|
||||
int TotalTracks,
|
||||
string? CoverPath,
|
||||
int? ReleaseYear,
|
||||
List<MusicReleaseType>? ReleaseTypes
|
||||
);
|
||||
+8
-17
@@ -7,20 +7,11 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.A
|
||||
/// <summary>
|
||||
/// Lightweight read model of an artist, containing only the fields needed to display the artist in a card-based grid or a list.
|
||||
/// </summary>
|
||||
public sealed record ArtistLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the artist.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the artist.
|
||||
/// </summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the image representing the artist, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the artist.</param>
|
||||
/// <param name="Name">The name of the artist.</param>
|
||||
/// <param name="CoverPath">The path of the image representing the artist, if available.</param>
|
||||
public sealed record ArtistLiteRow(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? CoverPath
|
||||
);
|
||||
+16
-37
@@ -7,40 +7,19 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
|
||||
/// <summary>
|
||||
/// Read model of a track returned by a randomized shuffle query, carrying everything the client needs to queue and play it.
|
||||
/// </summary>
|
||||
public sealed record ShuffleTrackRowDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the track.
|
||||
/// </summary>
|
||||
public required Guid TrackId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the track.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the album the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid AlbumId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the album the track belongs to.
|
||||
/// </summary>
|
||||
public required string AlbumTitle { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the artist the album belongs to.
|
||||
/// </summary>
|
||||
public required Guid ArtistId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the cover of the album, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
}
|
||||
/// <param name="TrackId">The Id of the track.</param>
|
||||
/// <param name="Title">The title of the track.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <param name="AlbumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="AlbumTitle">The title of the album the track belongs to.</param>
|
||||
/// <param name="ArtistId">The Id of the artist the album belongs to.</param>
|
||||
/// <param name="CoverPath">The path of the cover of the album, if available.</param>
|
||||
public sealed record ShuffleTrackRowDto(
|
||||
Guid TrackId,
|
||||
string Title,
|
||||
int DurationInSeconds,
|
||||
Guid AlbumId,
|
||||
string AlbumTitle,
|
||||
Guid ArtistId,
|
||||
string? CoverPath
|
||||
);
|
||||
+18
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the access information of a set of existing tracks.
|
||||
/// </summary>
|
||||
/// <param name="TrackCount">The number of distinct requested tracks that exist.</param>
|
||||
/// <param name="LibraryIds">The distinct Ids of the media libraries that contain those tracks.</param>
|
||||
[DebuggerDisplay("TrackCount: {TrackCount}; Libraries: {LibraryIds.Count}")]
|
||||
public sealed record TrackAccessSummaryDto(
|
||||
int TrackCount,
|
||||
IReadOnlyList<Guid> LibraryIds
|
||||
);
|
||||
+12
-27
@@ -7,30 +7,15 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
|
||||
/// <summary>
|
||||
/// Lightweight read model of a track, containing only the fields needed to display the track in a list.
|
||||
/// </summary>
|
||||
public sealed record TrackLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the track.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the track.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of the track on its disc.
|
||||
/// </summary>
|
||||
public int TrackNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of the disc the track belongs to, if applicable.
|
||||
/// </summary>
|
||||
public int? DiscNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the track.</param>
|
||||
/// <param name="Title">The title of the track.</param>
|
||||
/// <param name="TrackNumber">The number of the track on its disc.</param>
|
||||
/// <param name="DiscNumber">The number of the disc the track belongs to, if applicable.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
|
||||
public sealed record TrackLiteRow(
|
||||
Guid Id,
|
||||
string Title,
|
||||
int TrackNumber,
|
||||
int? DiscNumber,
|
||||
int DurationInSeconds
|
||||
);
|
||||
+10
-22
@@ -7,25 +7,13 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.WrittenContentLibrary.BookL
|
||||
/// <summary>
|
||||
/// Lightweight read model of a book, containing only the fields needed to display the book in a card-based grid or a list.
|
||||
/// </summary>
|
||||
public sealed record BookLiteRow
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the book.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title of the book.
|
||||
/// </summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the release year of the book (re-release year, if available, or original release year), if known.
|
||||
/// </summary>
|
||||
public int? ReleaseYear { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the image representing the cover of the book, if available.
|
||||
/// </summary>
|
||||
public string? CoverPath { get; init; }
|
||||
}
|
||||
/// <param name="Id">The Id of the book.</param>
|
||||
/// <param name="Title">The title of the book.</param>
|
||||
/// <param name="ReleaseYear">The release year of the book (re-release year, if available, or original release year), if known.</param>
|
||||
/// <param name="CoverPath">The path of the image representing the cover of the book, if available.</param>
|
||||
public sealed record BookLiteRow(
|
||||
Guid Id,
|
||||
string Title,
|
||||
int? ReleaseYear,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the result of appending entries to a playlist in one bulk operation.
|
||||
/// </summary>
|
||||
/// <param name="FirstPosition">The sparse order key of the first appended entry.</param>
|
||||
/// <param name="AddedCount">The number of entries appended.</param>
|
||||
[DebuggerDisplay("FirstPosition: {FirstPosition}; AddedCount: {AddedCount}")]
|
||||
public sealed record PlaylistBulkAddResultDto(
|
||||
long FirstPosition,
|
||||
int AddedCount
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist together with a window of its entries and their display data.
|
||||
/// </summary>
|
||||
/// <param name="Playlist">The stored playlist.</param>
|
||||
/// <param name="Entries">The requested window of entries.</param>
|
||||
public sealed record PlaylistDetailsDto(
|
||||
PlaylistEntity Playlist,
|
||||
IReadOnlyList<PlaylistEntryDto> Entries
|
||||
);
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Display data of the media item referenced by a playlist entry, together with its collection and creator.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track.</param>
|
||||
/// <param name="TrackTitle">The title of the track.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the track in seconds.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
|
||||
/// <param name="AlbumId">The Id of the album that contains the track.</param>
|
||||
/// <param name="AlbumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
|
||||
/// <param name="ArtistName">The name of the artist that produced the track.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
|
||||
public sealed record PlaylistEntryDisplayDto(
|
||||
Guid TrackId,
|
||||
string TrackTitle,
|
||||
int DurationInSeconds,
|
||||
Guid LibraryId,
|
||||
Guid AlbumId,
|
||||
string AlbumTitle,
|
||||
Guid ArtistId,
|
||||
string ArtistName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist entry together with the display data of the media item it references and its dense display position.
|
||||
/// </summary>
|
||||
/// <param name="Entry">The stored entry.</param>
|
||||
/// <param name="Display">The display data of the referenced media item, or <see langword="null"/> when it no longer exists.</param>
|
||||
/// <param name="DisplayPosition">The dense zero based position shown to the client.</param>
|
||||
public sealed record PlaylistEntryDto(
|
||||
PlaylistEntryEntity Entry,
|
||||
PlaylistEntryDisplayDto? Display,
|
||||
int DisplayPosition
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a playlist in a list, without its entries.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The description of the playlist, if applicable.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="EntryCount">The number of entries of the playlist.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the playlist was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
public sealed record PlaylistSummaryDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
int EntryCount,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a playlist.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; Type: {Type}")]
|
||||
public class PlaylistEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the playlist.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that owns the playlist.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the playlist.
|
||||
/// </summary>
|
||||
public required string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the playlist, if applicable.
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of media the playlist holds.
|
||||
/// </summary>
|
||||
public required PlaylistType Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ordered entries of the playlist.
|
||||
/// </summary>
|
||||
public List<PlaylistEntryEntity> Entries { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of entries the playlist holds.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public int EntryCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the concurrency token of the playlist.
|
||||
/// </summary>
|
||||
public long Version { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added.
|
||||
/// </summary>
|
||||
public required DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entity.
|
||||
/// </summary>
|
||||
public required Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entity was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entity.
|
||||
/// </summary>
|
||||
public required Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for an ordered entry of a playlist.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("Id: {Id}; MediaItemId: {MediaItemId}; MediaItemType: {MediaItemType}; Position: {Position}")]
|
||||
public class PlaylistEntryEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the entry.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the playlist the entry belongs to.
|
||||
/// </summary>
|
||||
public required Guid PlaylistId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media item referenced by the entry.
|
||||
/// </summary>
|
||||
public required Guid MediaItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of media item referenced by the entry.
|
||||
/// </summary>
|
||||
public PlaylistMediaItemType MediaItemType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sparse order key of the entry in the ordered entries of the playlist.
|
||||
/// </summary>
|
||||
public long Position { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entry was added.
|
||||
/// </summary>
|
||||
public DateTime CreatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that created the entry.
|
||||
/// </summary>
|
||||
public Guid CreatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional time and date when the entry was updated.
|
||||
/// </summary>
|
||||
public DateTime? UpdatedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional Id of the user that updated the entry.
|
||||
/// </summary>
|
||||
public Guid? UpdatedBy { get; set; }
|
||||
}
|
||||
@@ -129,4 +129,12 @@ public interface ITrackRepository : IRepository<TrackEntity>,
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
Task<Result<Updated>> ResetMetadataStatusForLibraryAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of tracks in <paramref name="trackIds"/> that exist, together with the distinct Ids of the libraries that contain them.
|
||||
/// </summary>
|
||||
/// <param name="trackIds">The Ids of the tracks whose access information is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the access summary of the existing tracks, or an error.</returns>
|
||||
Task<Result<TrackAccessSummaryDto>> GetAccessInfoByIdsAsync(IReadOnlyCollection<Guid> trackIds, CancellationToken cancellationToken);
|
||||
}
|
||||
+129
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for playlists.
|
||||
/// </summary>
|
||||
public interface IPlaylistRepository : IRepository<PlaylistEntity>,
|
||||
IInsertRepositoryAction<PlaylistEntity>,
|
||||
IUpdateRepositoryAction<PlaylistEntity>,
|
||||
IDeleteByIdRepositoryAction<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the playlist identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the playlist to get.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="shouldIncludeNavigationProperties">Whether the entries of the playlist should be loaded together with the playlist itself.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlist identified by <paramref name="id"/> and owned by <paramref name="userId"/>,
|
||||
/// <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldIncludeNavigationProperties = true, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlists of the user identified by <paramref name="userId"/>, ordered by their most recent activity.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose playlists are retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the playlists of the user, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<PlaylistSummaryDto>>> GetAllForUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the playlist to get.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlist details, <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Appends a batch of media items of one kind to the end of the ordered entries of a playlist of the user identified by
|
||||
/// <paramref name="userId"/>, using batched bulk inserts, and updates the activity time of the playlist in the same transaction.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist to append to.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="mediaItemIds">The Ids of the media items to append, in order. Duplicates are kept.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by every appended entry.</param>
|
||||
/// <param name="entryIds">The Ids to assign to the appended entries, in the same order as <paramref name="mediaItemIds"/>, or <see langword="null"/> to generate them.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the sparse order key of the first appended entry and the added count, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistBulkAddResultDto>> AddEntriesAsync(Guid playlistId, Guid userId, IReadOnlyList<Guid> mediaItemIds, PlaylistMediaItemType mediaItemType, IReadOnlyList<Guid>? entryIds, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <paramref name="userId"/>, in catalogue order, without materializing the scope.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist to append to.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="libraryId">The Id of the library whose media items are appended.</param>
|
||||
/// <param name="artistId">The Id of the artist the scope is limited to, or <see langword="null"/> for every artist of the library.</param>
|
||||
/// <param name="albumId">The Id of the album the scope is limited to, or <see langword="null"/> for every album of the scope.</param>
|
||||
/// <param name="mediaItemType">The kind of media item referenced by every appended entry.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the sparse order key of the first appended entry and the added count, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistBulkAddResultDto>> AddScopeEntriesAsync(Guid playlistId, Guid userId, Guid libraryId, Guid? artistId, Guid? albumId, PlaylistMediaItemType mediaItemType, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Moves one entry of a playlist of the user identified by <paramref name="userId"/> to a new dense position by changing only its
|
||||
/// sparse order key, and updates the activity time of the playlist in the same transaction.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist whose entry is moved.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="entryId">The Id of the entry to move.</param>
|
||||
/// <param name="targetPosition">The new zero based position of the entry.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful move, or an error.</returns>
|
||||
Task<Result<Updated>> MoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, int targetPosition, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes one entry of a playlist of the user identified by <paramref name="userId"/> by deleting only that row, and updates the
|
||||
/// activity time of the playlist in the same transaction.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist whose entry is removed.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="entryId">The Id of the entry to remove.</param>
|
||||
/// <param name="updatedOnUtc">The activity time to store on the playlist.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either zero, because sparse positions need no repositioning, or an error.
|
||||
/// </returns>
|
||||
Task<Result<int>> RemoveEntryAsync(Guid playlistId, Guid userId, Guid entryId, DateTime updatedOnUtc, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the entry that was just appended to a playlist of the user identified by <paramref name="userId"/>, together with the display details of the track it references.
|
||||
/// </summary>
|
||||
/// <param name="playlistId">The Id of the playlist the entry must belong to.</param>
|
||||
/// <param name="userId">The Id of the user the playlist must belong to.</param>
|
||||
/// <param name="entryId">The Id of the appended entry to get.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the entry details, <see langword="null"/> when the entry does not exist in that playlist of the user, or an error.
|
||||
/// </returns>
|
||||
Task<Result<PlaylistEntryDto?>> GetAppendedEntryDetailsForUserAsync(Guid playlistId, Guid userId, Guid entryId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -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
|
||||
/// </summary>
|
||||
IMusicPlayRecordRepository MusicPlayRecordRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist repository.
|
||||
/// </summary>
|
||||
IPlaylistRepository PlaylistRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddPlaylistEntriesRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddPlaylistEntriesRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddPlaylistEntriesCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddPlaylistEntriesCommand ToCommand(this AddPlaylistEntriesRequest request, string? playlistId)
|
||||
{
|
||||
return new AddPlaylistEntriesCommand(playlistId, request.TrackIds);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddPlaylistEntryRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddPlaylistEntryRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddPlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddPlaylistEntryCommand ToCommand(this AddPlaylistEntryRequest request, string? playlistId)
|
||||
{
|
||||
return new AddPlaylistEntryCommand(playlistId, request.TrackId);
|
||||
}
|
||||
}
|
||||
+23
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddPlaylistScopeEntriesRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddPlaylistScopeEntriesRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddPlaylistScopeEntriesCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddPlaylistScopeEntriesCommand ToCommand(this AddPlaylistScopeEntriesRequest request, string? playlistId)
|
||||
{
|
||||
return new AddPlaylistScopeEntriesCommand(playlistId, request.LibraryId, request.ArtistId, request.AlbumId);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="CreatePlaylistRequest"/>.
|
||||
/// </summary>
|
||||
public static class CreatePlaylistRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="CreatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static CreatePlaylistCommand ToCommand(this CreatePlaylistRequest request)
|
||||
{
|
||||
return new CreatePlaylistCommand(request.Name, request.Description, request.Type);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="MovePlaylistEntryRequest"/>.
|
||||
/// </summary>
|
||||
public static class MovePlaylistEntryRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="MovePlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <param name="playlistEntryId">The Id of the entry to move, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static MovePlaylistEntryCommand ToCommand(this MovePlaylistEntryRequest request, string? playlistId, string? playlistEntryId)
|
||||
{
|
||||
return new MovePlaylistEntryCommand(playlistId, playlistEntryId, request.TargetPosition);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistDetailsDto"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistDetailsDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="PlaylistResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The playlist details data to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntity"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="Playlist"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Playlist"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Playlist> ToDomainEntity(this PlaylistEntity repositoryEntity)
|
||||
{
|
||||
List<PlaylistEntry> 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<PlaylistEntry> 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<string>.FromNullable(repositoryEntity.Description),
|
||||
repositoryEntity.Type,
|
||||
entries,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntryDto"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntryDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="PlaylistEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The playlist entry data to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntryEntity"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntryEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="PlaylistEntry"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="PlaylistEntry"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<PlaylistEntry> ToDomainEntity(this PlaylistEntryEntity repositoryEntity)
|
||||
{
|
||||
return PlaylistEntry.Create(
|
||||
PlaylistEntryId.Create(repositoryEntity.Id),
|
||||
MediaItemId.Create(repositoryEntity.MediaItemId),
|
||||
repositoryEntity.MediaItemType,
|
||||
repositoryEntity.Position);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistEntry"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistEntryMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="PlaylistEntryEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist that owns the entry.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="Playlist"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="PlaylistEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="PlaylistSummaryDto"/>.
|
||||
/// </summary>
|
||||
public static class PlaylistSummaryDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="dto"/> to <see cref="PlaylistSummaryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="dto">The data transfer object to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static PlaylistSummaryResponse ToResponse(this PlaylistSummaryDto dto)
|
||||
{
|
||||
return new PlaylistSummaryResponse(
|
||||
dto.Id,
|
||||
dto.Name,
|
||||
dto.Description,
|
||||
dto.Type,
|
||||
dto.EntryCount,
|
||||
dto.CreatedOnUtc,
|
||||
dto.UpdatedOnUtc);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="UpdatePlaylistRequest"/>.
|
||||
/// </summary>
|
||||
public static class UpdatePlaylistRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="UpdatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static UpdatePlaylistCommand ToCommand(this UpdatePlaylistRequest request, string? playlistId)
|
||||
{
|
||||
return new UpdatePlaylistCommand(playlistId, request.Name, request.Description);
|
||||
}
|
||||
}
|
||||
+19
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="TrackIds">The unique identifiers of the tracks to add, in the order they must take.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackCount: {TrackIds.Count}")]
|
||||
public record AddPlaylistEntriesCommand(
|
||||
string? PlaylistId,
|
||||
List<Guid>? TrackIds
|
||||
) : ICommand;
|
||||
+120
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntriesCommandHandler : ICommandHandler<AddPlaylistEntriesCommand, Result<PlaylistEntriesAddedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddPlaylistEntriesCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntriesCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddPlaylistEntriesCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<AddPlaylistEntriesCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the number of appended entries and the playlist activity time, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntriesAddedResponse>> HandleAsync(AddPlaylistEntriesCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the 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<PlaylistEntity?> 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<Guid> distinctTrackIds = [.. command.TrackIds!.Distinct()];
|
||||
Result<TrackAccessSummaryDto> 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<ILibraryOwnershipPolicy>(
|
||||
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<PlaylistBulkAddResultDto> 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);
|
||||
}
|
||||
}
|
||||
+42
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddPlaylistEntriesCommand"/>.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntriesCommandValidator : AbstractValidator<AddPlaylistEntriesCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntriesCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track to add.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; TrackId: {TrackId}")]
|
||||
public record AddPlaylistEntryCommand(
|
||||
string? PlaylistId,
|
||||
Guid? TrackId
|
||||
) : ICommand;
|
||||
+124
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntryCommandHandler : ICommandHandler<AddPlaylistEntryCommand, Result<PlaylistEntryAddedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddPlaylistEntryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddPlaylistEntryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<AddPlaylistEntryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the appended entry and the playlist activity time, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntryAddedResponse>> HandleAsync(AddPlaylistEntryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the 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<PlaylistEntity?> 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<TrackEntity?> 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<ILibraryOwnershipPolicy>(
|
||||
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<PlaylistBulkAddResultDto> 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<PlaylistEntryDto?> 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);
|
||||
}
|
||||
}
|
||||
+38
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddPlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
public class AddPlaylistEntryCommandValidator : AbstractValidator<AddPlaylistEntryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistEntryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist, taken from the route.</param>
|
||||
/// <param name="LibraryId">The Id of the music library the scope belongs to.</param>
|
||||
/// <param name="ArtistId">The Id of the artist the scope is limited to, if applicable.</param>
|
||||
/// <param name="AlbumId">The Id of the album the scope is limited to, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")]
|
||||
public record AddPlaylistScopeEntriesCommand(
|
||||
string? PlaylistId,
|
||||
Guid? LibraryId,
|
||||
Guid? ArtistId,
|
||||
Guid? AlbumId
|
||||
) : ICommand;
|
||||
+107
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add every track of a music library, an artist or an album to a playlist.
|
||||
/// </summary>
|
||||
public class AddPlaylistScopeEntriesCommandHandler : ICommandHandler<AddPlaylistScopeEntriesCommand, Result<PlaylistEntriesAddedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<AddPlaylistScopeEntriesCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddPlaylistScopeEntriesCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<AddPlaylistScopeEntriesCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add every track of a music library, an artist or an album to a playlist.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the number of appended entries and the playlist activity time, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntriesAddedResponse>> HandleAsync(AddPlaylistScopeEntriesCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the 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<PlaylistEntity?> 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<ILibraryOwnershipPolicy>(
|
||||
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<PlaylistBulkAddResultDto> 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);
|
||||
}
|
||||
}
|
||||
+41
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddPlaylistScopeEntriesCommand"/>.
|
||||
/// </summary>
|
||||
public class AddPlaylistScopeEntriesCommandValidator : AbstractValidator<AddPlaylistScopeEntriesCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+20
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Command for creating a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The optional description of the playlist.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record CreatePlaylistCommand(
|
||||
string? Name,
|
||||
string? Description,
|
||||
PlaylistType? Type
|
||||
) : ICommand;
|
||||
+105
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to create a playlist of the current user.
|
||||
/// </summary>
|
||||
public class CreatePlaylistCommandHandler : ICommandHandler<CreatePlaylistCommand, Result<PlaylistResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<CreatePlaylistCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreatePlaylistCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public CreatePlaylistCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<CreatePlaylistCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to create a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the created <see cref="PlaylistResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistResponse>> HandleAsync(CreatePlaylistCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
Result<Playlist> createPlaylistResult = Playlist.Create(
|
||||
UserId.Create(userId),
|
||||
command.Name!,
|
||||
Optional<string>.FromNullable(command.Description),
|
||||
command.Type!.Value);
|
||||
if (createPlaylistResult.IsFailure)
|
||||
return createPlaylistResult.Errors;
|
||||
Playlist playlist = createPlaylistResult.Value;
|
||||
|
||||
Result<Created> insertResult = await _unitOfWork.PlaylistRepository.InsertAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
return insertResult.Errors;
|
||||
|
||||
Result<Success> 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<PlaylistDetailsDto?> 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();
|
||||
}
|
||||
}
|
||||
+40
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="CreatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
public class CreatePlaylistCommandValidator : AbstractValidator<CreatePlaylistCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CreatePlaylistCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.DeletePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Command for deleting a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}")]
|
||||
public record DeletePlaylistCommand(
|
||||
string? PlaylistId
|
||||
) : ICommand;
|
||||
+102
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to delete a playlist of the current user.
|
||||
/// </summary>
|
||||
public class DeletePlaylistCommandHandler : ICommandHandler<DeletePlaylistCommand, Result<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<DeletePlaylistCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletePlaylistCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public DeletePlaylistCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<DeletePlaylistCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to delete a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public async Task<Result<Deleted>> HandleAsync(DeletePlaylistCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route 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<PlaylistEntity?> 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<Playlist> toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Playlist playlist = toDomainEntityResult.Value;
|
||||
|
||||
Result<Deleted> deleteResult = playlist.Delete();
|
||||
if (deleteResult.IsFailure)
|
||||
return deleteResult.Errors;
|
||||
|
||||
Result<Deleted> deletePlaylistResult = await _unitOfWork.PlaylistRepository.DeleteByIdAsync(playlist.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (deletePlaylistResult.IsFailure)
|
||||
return deletePlaylistResult.Errors;
|
||||
|
||||
Result<Success> 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;
|
||||
}
|
||||
}
|
||||
+29
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="DeletePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
public class DeletePlaylistCommandValidator : AbstractValidator<DeletePlaylistCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeletePlaylistCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Command for moving one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="PlaylistEntryId">The unique identifier of the entry to move, taken from the route.</param>
|
||||
/// <param name="TargetPosition">The new zero based position of the entry.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}; TargetPosition: {TargetPosition}")]
|
||||
public record MovePlaylistEntryCommand(
|
||||
string? PlaylistId,
|
||||
string? PlaylistEntryId,
|
||||
int? TargetPosition
|
||||
) : ICommand;
|
||||
+80
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to move one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
public class MovePlaylistEntryCommandHandler : ICommandHandler<MovePlaylistEntryCommand, Result<PlaylistEntryMovedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<MovePlaylistEntryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovePlaylistEntryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public MovePlaylistEntryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IValidator<MovePlaylistEntryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to move one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the moved entry and its position, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntryMovedResponse>> HandleAsync(MovePlaylistEntryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifiers are non-empty Guids before this point.
|
||||
Guid 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<Updated> 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);
|
||||
}
|
||||
}
|
||||
+47
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="MovePlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
public class MovePlaylistEntryCommandValidator : AbstractValidator<MovePlaylistEntryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovePlaylistEntryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry;
|
||||
|
||||
/// <summary>
|
||||
/// Command for removing an entry from a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="PlaylistEntryId">The unique identifier of the entry to remove, taken from the route.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; PlaylistEntryId: {PlaylistEntryId}")]
|
||||
public record RemovePlaylistEntryCommand(
|
||||
string? PlaylistId,
|
||||
string? PlaylistEntryId
|
||||
) : ICommand;
|
||||
+78
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to remove an entry from a playlist of the current user.
|
||||
/// </summary>
|
||||
public class RemovePlaylistEntryCommandHandler : ICommandHandler<RemovePlaylistEntryCommand, Result<PlaylistEntryRemovedResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<RemovePlaylistEntryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemovePlaylistEntryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public RemovePlaylistEntryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IValidator<RemovePlaylistEntryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to remove an entry from a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the removed entry with zero repositioned entries, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistEntryRemovedResponse>> HandleAsync(RemovePlaylistEntryCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifiers are non-empty Guids before this point.
|
||||
Guid 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<int> 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);
|
||||
}
|
||||
}
|
||||
+38
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="RemovePlaylistEntryCommand"/>.
|
||||
/// </summary>
|
||||
public class RemovePlaylistEntryCommandValidator : AbstractValidator<RemovePlaylistEntryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemovePlaylistEntryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Commands.UpdatePlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The optional description of the playlist.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}")]
|
||||
public record UpdatePlaylistCommand(
|
||||
string? PlaylistId,
|
||||
string? Name,
|
||||
string? Description
|
||||
) : ICommand;
|
||||
+112
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
public class UpdatePlaylistCommandHandler : ICommandHandler<UpdatePlaylistCommand, Result<PlaylistDetailsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<UpdatePlaylistCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaylistCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public UpdatePlaylistCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<UpdatePlaylistCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the updated <see cref="PlaylistResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistDetailsResponse>> HandleAsync(UpdatePlaylistCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route 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<PlaylistEntity?> 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<Playlist> toDomainEntityResult = getPlaylistResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Playlist playlist = toDomainEntityResult.Value;
|
||||
|
||||
Result<Updated> updateDetailsResult = playlist.UpdateDetails(command.Name!, Optional<string>.FromNullable(command.Description));
|
||||
if (updateDetailsResult.IsFailure)
|
||||
return updateDetailsResult.Errors;
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.PlaylistRepository.UpdateAsync(playlist.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
Result<Success> 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);
|
||||
}
|
||||
}
|
||||
+41
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdatePlaylistCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdatePlaylistCommandValidator : AbstractValidator<UpdatePlaylistCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdatePlaylistCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a playlist of the current user, together with a window of its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The unique identifier of the playlist, taken from the route.</param>
|
||||
/// <param name="Offset">The zero based position of the first entry to return.</param>
|
||||
/// <param name="Limit">The maximum number of entries to return in this window.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; Offset: {Offset}; Limit: {Limit}")]
|
||||
public record GetPlaylistQuery(
|
||||
string? PlaylistId,
|
||||
int Offset = 0,
|
||||
int Limit = PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE
|
||||
) : IQuery;
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a playlist of the current user, together with its ordered entries.
|
||||
/// </summary>
|
||||
public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<PlaylistResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<GetPlaylistQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPlaylistQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator<GetPlaylistQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a playlist of the current user, together with its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the requested <see cref="PlaylistResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistResponse>> HandleAsync(GetPlaylistQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<PlaylistDetailsDto?> 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<Guid> libraryIds = [.. playlist.Entries
|
||||
.Select(entry => entry.Display?.LibraryId ?? Guid.Empty)
|
||||
.Where(libraryId => libraryId != Guid.Empty)
|
||||
.Distinct()];
|
||||
Dictionary<Guid, bool> libraryAccess = [];
|
||||
foreach (Guid libraryId in libraryIds)
|
||||
{
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
libraryAccess[libraryId] = canAccessLibrary;
|
||||
}
|
||||
|
||||
if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary))
|
||||
{
|
||||
List<PlaylistEntryDto> 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();
|
||||
}
|
||||
}
|
||||
+37
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetPlaylistQuery"/>.
|
||||
/// </summary>
|
||||
public class GetPlaylistQueryValidator : AbstractValidator<GetPlaylistQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistQueryValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
|
||||
/// <summary>
|
||||
/// The bounds of one playlist entry read window.
|
||||
/// </summary>
|
||||
public static class PlaylistWindow
|
||||
{
|
||||
/// <summary>
|
||||
/// The default number of entries a single read window returns.
|
||||
/// </summary>
|
||||
public const int DEFAULT_ENTRY_WINDOW_SIZE = 200;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum number of entries a single read window may return.
|
||||
/// </summary>
|
||||
public const int MAXIMUM_ENTRY_WINDOW_SIZE = 1000;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Playlists.Queries.GetPlaylists;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the playlists of the current user.
|
||||
/// </summary>
|
||||
public record GetPlaylistsQuery : IQuery;
|
||||
+60
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the playlists of the current user.
|
||||
/// </summary>
|
||||
public class GetPlaylistsQueryHandler : IQueryHandler<GetPlaylistsQuery, Result<PlaylistSummaryResponse[]>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlaylistsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
public GetPlaylistsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the playlists of the current user.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlists of the current user, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistSummaryResponse[]>> 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<IReadOnlyList<PlaylistSummaryDto>> 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for adding several tracks to a playlist of the current user, in order.
|
||||
/// </summary>
|
||||
/// <param name="TrackIds">The Ids of the tracks to add, in the order they must take. Required.</param>
|
||||
[DebuggerDisplay("TrackCount: {TrackIds.Count}")]
|
||||
public record AddPlaylistEntriesRequest(
|
||||
List<Guid>? TrackIds
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for adding a track to a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track to add. Required.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record AddPlaylistEntryRequest(
|
||||
Guid? TrackId
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to add every track of a music library, an artist or an album to a playlist, resolved on the server.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the music library the scope belongs to. Required.</param>
|
||||
/// <param name="ArtistId">The Id of the artist the scope is limited to. Optional.</param>
|
||||
/// <param name="AlbumId">The Id of the album the scope is limited to. Optional.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}; ArtistId: {ArtistId}; AlbumId: {AlbumId}")]
|
||||
public record AddPlaylistScopeEntriesRequest(
|
||||
Guid LibraryId,
|
||||
Guid? ArtistId = null,
|
||||
Guid? AlbumId = null
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for creating a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the playlist. Required.</param>
|
||||
/// <param name="Description">The description of the playlist. Optional.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds. Required.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record CreatePlaylistRequest(
|
||||
string? Name,
|
||||
string? Description,
|
||||
PlaylistType? Type
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a window of the entries of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Offset">The zero based position of the first entry to return. Optional; defaults to 0.</param>
|
||||
/// <param name="Limit">The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")]
|
||||
public record GetPlaylistRequest(
|
||||
int? Offset,
|
||||
int? Limit
|
||||
);
|
||||
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for moving one entry of a playlist of the current user to a new position.
|
||||
/// </summary>
|
||||
/// <param name="TargetPosition">The new zero based position of the entry. Required.</param>
|
||||
[DebuggerDisplay("TargetPosition: {TargetPosition}")]
|
||||
public record MovePlaylistEntryRequest(
|
||||
int? TargetPosition
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for updating the details of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Name">The name of the playlist. Required.</param>
|
||||
/// <param name="Description">The description of the playlist. Optional.</param>
|
||||
[DebuggerDisplay("Name: {Name}")]
|
||||
public record UpdatePlaylistRequest(
|
||||
string? Name,
|
||||
string? Description
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the editable scalars of a playlist after a details update.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The description of the playlist, if applicable.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}")]
|
||||
public sealed record PlaylistDetailsResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the result of appending several tracks to a playlist, without returning the whole playlist.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist the entries were added to.</param>
|
||||
/// <param name="AddedCount">The number of entries that were appended, including repeated tracks.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; AddedCount: {AddedCount}")]
|
||||
public sealed record PlaylistEntriesAddedResponse(
|
||||
Guid PlaylistId,
|
||||
int AddedCount,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the entry that was appended to a playlist, together with its playlist and the new activity time of the playlist.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist the entry was added to.</param>
|
||||
/// <param name="Entry">The added entry, with the display details of the media item it references.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; Entry: {Entry.Id}")]
|
||||
public sealed record PlaylistEntryAddedResponse(
|
||||
Guid PlaylistId,
|
||||
PlaylistEntryResponse Entry,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the result of moving one entry of a playlist to a new position.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist whose entry was moved.</param>
|
||||
/// <param name="EntryId">The Id of the moved entry.</param>
|
||||
/// <param name="Position">The new zero based position of the entry.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; EntryId: {EntryId}; Position: {Position}")]
|
||||
public sealed record PlaylistEntryMovedResponse(
|
||||
Guid PlaylistId,
|
||||
Guid EntryId,
|
||||
int Position,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for the result of removing an entry from a playlist.
|
||||
/// </summary>
|
||||
/// <param name="PlaylistId">The Id of the playlist the entry was removed from.</param>
|
||||
/// <param name="RemovedEntryId">The Id of the removed entry.</param>
|
||||
/// <param name="RepositionedCount">Always zero, because sparse order keys need no remaining entries to be repositioned.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}; RemovedEntryId: {RemovedEntryId}; RepositionedCount: {RepositionedCount}")]
|
||||
public sealed record PlaylistEntryRemovedResponse(
|
||||
Guid PlaylistId,
|
||||
Guid RemovedEntryId,
|
||||
int RepositionedCount,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for an ordered entry of a playlist.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the entry.</param>
|
||||
/// <param name="MediaItemId">The Id of the media item referenced by the entry.</param>
|
||||
/// <param name="MediaItemType">The kind of media item referenced by the entry.</param>
|
||||
/// <param name="Position">The zero based position of the entry in the playlist.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item no longer exists.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when the item no longer exists.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when the item no longer exists.</param>
|
||||
/// <param name="MediaItemTitle">The title of the media item, or an empty string when the item no longer exists.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when the item no longer exists.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when the item no longer exists.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the media item in seconds, or zero when the item no longer exists.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the collection, if available.</param>
|
||||
[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
|
||||
);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for a playlist together with its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The description of the playlist, if applicable.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="Entries">The ordered entries of the requested window of the playlist.</param>
|
||||
/// <param name="EntryCount">The number of entries the playlist holds, even when only a window of them is returned.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the playlist was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; EntryCount: {EntryCount}; Window: {Entries.Count}")]
|
||||
public sealed record PlaylistResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
IReadOnlyList<PlaylistEntryResponse> Entries,
|
||||
int EntryCount,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for a playlist in a list, without its entries.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The description of the playlist, if applicable.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="EntryCount">The number of entries of the playlist.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the playlist was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[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
|
||||
);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="PlaylistEntity"/> entity.
|
||||
/// </summary>
|
||||
public class PlaylistConfiguration : IEntityTypeConfiguration<PlaylistEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="PlaylistEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<PlaylistEntity> 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<UserEntity>()
|
||||
.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<string>()
|
||||
.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 });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="PlaylistEntryEntity"/> entity.
|
||||
/// </summary>
|
||||
public class PlaylistEntryConfiguration : IEntityTypeConfiguration<PlaylistEntryEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="PlaylistEntryEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<PlaylistEntryEntity> 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<string>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,21 @@ namespace Lumina.DataAccess.Common.Dapper;
|
||||
/// Maps <see cref="Guid"/> values to and from the TEXT representation used by the SQLite provider.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The SQLite provider stores <see cref="Guid"/> columns as TEXT, and Dapper falls back to Convert.ChangeType when materializing such
|
||||
/// columns into <see cref="Guid"/> properties. <see cref="Guid"/> has no string <see cref="TypeConverter"/>, so that conversion throws
|
||||
/// an <see cref="InvalidCastException"/>; this handler performs the conversion explicitly instead.
|
||||
/// The SQLite provider stores <see cref="Guid"/> columns as upper case TEXT. Dapper falls back to Convert.ChangeType when materializing
|
||||
/// such columns into <see cref="Guid"/> properties. <see cref="Guid"/> has no string <see cref="TypeConverter"/>, so that conversion
|
||||
/// throws an <see cref="InvalidCastException"/>; 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.
|
||||
/// </remarks>
|
||||
internal sealed class SqliteGuidTypeHandler : SqlMapper.TypeHandler<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets the parameter value to the TEXT representation of the <see cref="Guid"/> value, keeping writes consistent with reads.
|
||||
/// Sets the parameter value to the upper case TEXT representation the SQLite provider uses for <see cref="Guid"/> columns.
|
||||
/// </summary>
|
||||
/// <param name="parameter">The database parameter to set.</param>
|
||||
/// <param name="value">The <see cref="Guid"/> value to store.</param>
|
||||
public override void SetValue(IDbDataParameter parameter, Guid value)
|
||||
{
|
||||
parameter.Value = value.ToString();
|
||||
parameter.Value = value.ToString().ToUpperInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+3673
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsPlaylists : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Playlists",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Name = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
|
||||
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
|
||||
Type = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true),
|
||||
Version = table.Column<long>(type: "INTEGER", nullable: false, defaultValue: 0L),
|
||||
EntryCount = table.Column<int>(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<Guid>(type: "TEXT", nullable: false),
|
||||
PlaylistId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
MediaItemId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
MediaItemType = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
Position = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(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" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "PlaylistEntries");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Playlists");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<int>("EntryCount")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(0)
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<long>("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<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("MediaItemType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("PlaylistId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<long>("Position")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("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<Guid>("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");
|
||||
|
||||
@@ -16,8 +16,9 @@ internal static class CollectionReconciler
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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
|
||||
/// <paramref name="shouldReplace"/> 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.
|
||||
/// <paramref name="shouldReplace"/> reports that their non-key values changed, in which case only that item is replaced, or <paramref name="applyMatched"/> 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.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TExisting">The type of the tracked items.</typeparam>
|
||||
/// <typeparam name="TIncoming">The type of the desired items.</typeparam>
|
||||
@@ -28,13 +29,15 @@ internal static class CollectionReconciler
|
||||
/// <param name="incomingKeySelector">Selects the matching key of a desired item.</param>
|
||||
/// <param name="shouldReplace">Determines whether a matched tracked item must be replaced, because a non-key value changed.</param>
|
||||
/// <param name="createNew">Creates the entity used for a desired item that is not matched by any tracked item.</param>
|
||||
/// <param name="applyMatched">Applies the incoming non-key values onto a matched tracked item, when the caller updates matched items in place instead of replacing them.</param>
|
||||
public static void Reconcile<TExisting, TIncoming, TKey>(
|
||||
ICollection<TExisting> existingItems,
|
||||
IEnumerable<TIncoming> incomingItems,
|
||||
Func<TExisting, TKey> existingKeySelector,
|
||||
Func<TIncoming, TKey> incomingKeySelector,
|
||||
Func<TExisting, TIncoming, bool> shouldReplace,
|
||||
Func<TIncoming, TExisting> createNew)
|
||||
Func<TIncoming, TExisting> createNew,
|
||||
Action<TExisting, TIncoming>? 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
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<BookLiteRow> liteRowsQuery = booksQuery.Select(book => new BookLiteRow
|
||||
{
|
||||
Id = book.Id,
|
||||
Title = book.Title,
|
||||
ReleaseYear = book.ReReleaseYear ?? book.OriginalReleaseYear,
|
||||
CoverPath = book.Artwork
|
||||
IQueryable<BookLiteRow> 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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -275,25 +275,23 @@ internal sealed class AlbumRepository : IAlbumRepository
|
||||
public async Task<Result<PaginatedResultDto<AlbumLiteRow>>> 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<AlbumLiteRow> 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)
|
||||
{
|
||||
|
||||
@@ -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<ArtistLiteRow> 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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of tracks in <paramref name="trackIds"/> that exist, together with the distinct Ids of the libraries that contain them.
|
||||
/// </summary>
|
||||
/// <param name="trackIds">The Ids of the tracks whose access information is retrieved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the access summary of the existing tracks, or an error.</returns>
|
||||
public async Task<Result<TrackAccessSummaryDto>> GetAccessInfoByIdsAsync(IReadOnlyCollection<Guid> 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<Guid> libraryIds = [];
|
||||
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
{
|
||||
List<TrackLibraryCount> 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]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The number of requested tracks that exist in one library.
|
||||
/// </summary>
|
||||
private sealed class TrackLibraryCount
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the library.
|
||||
/// </summary>
|
||||
public Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of requested tracks in the library.
|
||||
/// </summary>
|
||||
public int TrackCount { get; set; }
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<ScheduledJobExecutionEntity> ScheduledJobExecutions { get; set; } = null!;
|
||||
public virtual DbSet<SchedulerDisplayPreferencesEntity> SchedulerDisplayPreferences { get; set; } = null!;
|
||||
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the permission repository.
|
||||
@@ -387,6 +390,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist repository.
|
||||
/// </summary>
|
||||
public IPlaylistRepository PlaylistRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_playlistRepository ??= new PlaylistRepository(_luminaDbContext);
|
||||
return _playlistRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media item an ordered playlist entry can reference.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum PlaylistMediaItemType
|
||||
{
|
||||
/// <summary>
|
||||
/// An entry that references a music track.
|
||||
/// </summary>
|
||||
MusicTrack,
|
||||
|
||||
/// <summary>
|
||||
/// An entry that references a video file.
|
||||
/// </summary>
|
||||
VideoFile,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media a playlist can hold.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum PlaylistType
|
||||
{
|
||||
/// <summary>
|
||||
/// A playlist whose ordered entries reference music tracks.
|
||||
/// </summary>
|
||||
Music,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Playlist error types.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
+54
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a media item, duplicated from the media library bounded contexts to keep the cross bounded context references decoupled.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class MediaItemId : EntityId<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaItemId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private MediaItemId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="MediaItemId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
|
||||
public static MediaItemId CreateUnique()
|
||||
{
|
||||
return new MediaItemId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="MediaItemId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="MediaItemId"/> instance.</param>
|
||||
/// <returns>The created <see cref="MediaItemId"/> instance.</returns>
|
||||
public static MediaItemId Create(Guid value)
|
||||
{
|
||||
return new MediaItemId(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of items that define equality of the object.
|
||||
/// </summary>
|
||||
/// <returns>A list of items defining the equality.</returns>
|
||||
public override IEnumerable<object> GetEqualityComponents()
|
||||
{
|
||||
yield return Value;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user