mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds favorites and aligns playlist and favorite pagination
This commit is contained in:
1 parent
2e9f7d8496
commit
525ac1348d
193 files changed
+10944
-643
No files matched your search
@@ -37,6 +37,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. You can also build your own playlists, order them the way you want and play them in the browser.
|
||||
- **Favorites.** Mark the artists, albums, tracks and books you love as favorites and come back to them from one page, filtered by kind. Favorites are private to your account.
|
||||
- **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.
|
||||
|
||||
@@ -90,11 +90,24 @@ From the playlists page you can open a playlist or select **Create** to open the
|
||||
|
||||
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.
|
||||
|
||||
## Favorites
|
||||
|
||||
A favorite is a mark you place on an artist, album, track or book so you can find it again quickly. Favorites belong to your account and are not shared with other users. Marking an item never changes the item or its files. Videos and photos are not available as favorites yet.
|
||||
|
||||
Select the heart on an item's card, or on its row on an album page, to add or remove the mark. A blue heart means the item is not a favorite; a red heart means it is.
|
||||
|
||||
The **Favorites** page in the library section lists everything you marked, most recent first, with a count that follows the filter.
|
||||
|
||||
- **Filter by kind** with the **Show** picker.
|
||||
- **Open an item** from its card.
|
||||
- **Remove a favorite** with the heart on its card.
|
||||
- **Load more** when the list is long, or **Retry** if it does not load.
|
||||
|
||||
A favorite whose item was deleted, or whose library you can no longer access, stays in the list as an unavailable card so you can still remove it.
|
||||
|
||||
## Editing what is catalogued
|
||||
|
||||
Both book and music pages double as editors for the items that were scanned in. A book's details page groups its fields into general and release information, language and original language, genres, tags, identifiers, ISBNs, contributors and ratings, and lets you replace its cover. An artist's page lists the artist's albums first, then groups its fields into general information, contributors, ratings, genres, tags, aliases, areas and identifiers, and lets you replace the artist's cover. An album page groups its fields into general information, contributors, ratings, genres, tags, release types, release information, language and original language, and identifiers, and lets you replace the album's cover. A track page groups its fields into general information, contributors, ratings, genres, tags, moods, release information, language and original language, work, ISRCs, identifiers and audio properties. Saving sends the changes back to the server, and a confirmation or an error is shown in the corner of the screen.
|
||||
|
||||
Changes you make here live in Lumina's catalogue.
|
||||
Both book and music pages double as editors for the items that were scanned in. A book's details page groups its fields into general and release information, language and original language, genres, tags, identifiers, ISBNs, contributors and ratings, and lets you replace its cover. An artist's page lists the artist's albums first, then groups its fields into general information, contributors, ratings, genres, tags, aliases, areas and identifiers, and lets you replace the artist's cover. An album page groups its fields into general information, contributors, ratings, genres, tags, release types, release information, language and original language, and identifiers, and lets you replace the album's cover. A track page groups its fields into general information, contributors, ratings, genres, tags, moods, release information, language and original language, work, ISRCs, identifiers and audio properties. Saving applies the changes to Lumina's catalogue.
|
||||
|
||||
## The file system browser
|
||||
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
# Lumina API
|
||||
|
||||
- [Lumina API](#lumina-api)
|
||||
- [Favorites](#favorites)
|
||||
- [Add Favorite](#add-favorite)
|
||||
- [Add Favorite Request](#add-favorite-request)
|
||||
- [Add Favorite Response](#add-favorite-response)
|
||||
- [Remove Favorite](#remove-favorite)
|
||||
- [Remove Favorite Request](#remove-favorite-request)
|
||||
- [Remove Favorite Response](#remove-favorite-response)
|
||||
- [Get Favorites](#get-favorites)
|
||||
- [Get Favorites Request](#get-favorites-request)
|
||||
- [Get Favorites Response](#get-favorites-response)
|
||||
- [Get Favorite Status](#get-favorite-status)
|
||||
- [Get Favorite Status Request](#get-favorite-status-request)
|
||||
- [Get Favorite Status Response](#get-favorite-status-response)
|
||||
- [Media Kinds](#media-kinds)
|
||||
- [Scoping and Library Access](#scoping-and-library-access)
|
||||
- [Errors](#errors)
|
||||
- [Pagination Limits](#pagination-limits)
|
||||
|
||||
## Favorites
|
||||
|
||||
A favorite is the marker the current user places on a media item of any media kind. It references the item only by its kind and its Id, so the same four operations serve music artists, albums and tracks, books, and the kinds that are planned. A favorite belongs to the user that created it, and only that user can list it, check it or remove it. Every route is under `users/me`, because it always acts on the currently authenticated user, and every operation requires authentication.
|
||||
|
||||
Favorites are independent of the catalogue they point to. A favorite stores the kind and the Id of the item without a foreign key to it, so deleting the item from its library does not delete the favorite. A favorite is deleted together with the user that owns it. A favorite whose item was deleted, or whose library the user can no longer access, is still listed, as an unavailable item with empty display fields, so that its owner can see it and remove it.
|
||||
|
||||
All the responses of the four operations are private to the authenticated user: they carry `Cache-Control: private, no-store` and `Vary: Authorization`.
|
||||
|
||||
### Add Favorite
|
||||
|
||||
#### Add Favorite Request
|
||||
|
||||
```js
|
||||
POST api/v1/users/me/favorites
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"mediaKind": "MusicTrack",
|
||||
"mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `mediaKind` | string | yes | The kind of the media item: `MusicArtist`, `MusicAlbum`, `MusicTrack` or `Book`. `Video` and `Photo` are planned kinds and are rejected, see [Media Kinds](#media-kinds). |
|
||||
| `mediaItemId` | Guid | yes | The Id of the media item. It cannot be the empty Guid. |
|
||||
|
||||
Marks the media item as a favorite of the current user. The request is validated first, and then the media item is looked up in the catalogue of its kind. The item must exist, and the library that contains it must be accessible to the current user, see [Scoping and Library Access](#scoping-and-library-access). The user is always the authenticated user, so no user Id is accepted in the body.
|
||||
|
||||
#### Add Favorite Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
|
||||
"mediaKind": "MusicTrack",
|
||||
"mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
|
||||
"favoritedOnUtc": "2026-10-21T12:00:00.0000000Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `id` | The Id of the favorite. |
|
||||
| `mediaKind` | The kind of the favorited media item. |
|
||||
| `mediaItemId` | The Id of the favorited media item. |
|
||||
| `favoritedOnUtc` | The date and time when the item was favorited. |
|
||||
|
||||
The response is `200 Ok` both when the favorite was created and when it already existed, so a client does not need to tell the two apart. The favorite is read back from storage after it is saved, so `favoritedOnUtc` is the stored value. A favorite that was created raises a `FavoriteAdded` domain event; an existing favorite raises none.
|
||||
|
||||
### Remove Favorite
|
||||
|
||||
#### Remove Favorite Request
|
||||
|
||||
```js
|
||||
DELETE api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
| Route value | Meaning |
|
||||
| --- | --- |
|
||||
| `mediaKind` | The name of the media kind, matched case insensitively. Only the member names are accepted: a number that would parse as a kind is rejected. |
|
||||
| `mediaItemId` | The Id of the media item. It must be a Guid and cannot be the empty Guid. |
|
||||
|
||||
Removes the favorite of the current user on the media item identified by the route. Removal is scoped to the authenticated user and never touches another user's favorite. It does not look the media item up and does not evaluate the library access rule, so a user can always remove their own favorite even when the item was deleted or its library is no longer accessible. Another user's favorite is never visible to them, so it cannot be removed through this route. Removing a media kind that is planned but not supported is not an error by itself: it finds no favorite and the request succeeds without changing anything.
|
||||
|
||||
#### Remove Favorite Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
The response body is an empty JSON object.
|
||||
|
||||
Removing an item that the current user did not favorite succeeds without changing anything, and the same is true for a favorite of another user, which is never visible to the current user. Removing is therefore idempotent: the second removal of the same favorite also returns `200 Ok` and raises no event. A favorite that was actually removed raises a `FavoriteRemoved` domain event.
|
||||
|
||||
### Get Favorites
|
||||
|
||||
#### Get Favorites Request
|
||||
|
||||
```js
|
||||
GET api/v1/users/me/favorites?mediaKind=MusicTrack¤tPage=1&perPage=200
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
| Query parameter | Type | Required | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `mediaKind` | string | no | Restricts the list to one kind: `MusicArtist`, `MusicAlbum`, `MusicTrack` or `Book`. Every kind is returned when it is omitted. |
|
||||
| `currentPage` | integer | no | The one based page of favorites to return. Defaults to `1` when `perPage` is provided. Values below `1` are raised to `1`. |
|
||||
| `perPage` | integer | no | The number of favorites per page. Defaults to `200` when `currentPage` is provided. Values below `1` are raised to `1`, and there is no maximum. |
|
||||
|
||||
Returns the favorites of the current user, from the most recently favorited. The page bounds one response, not the number of favorites a user can have: a client reads the next page until `currentPage` reaches `numberOfPages`, and `count` reports the total. When neither `currentPage` nor `perPage` is provided, every matching favorite is returned in a single page, the same way the other paginated collections of the API behave when pagination is omitted.
|
||||
|
||||
#### Get Favorites Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"mediaKind": "MusicTrack",
|
||||
"mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
|
||||
"isAvailable": true,
|
||||
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
|
||||
"title": "Bohemian Rhapsody",
|
||||
"collectionId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
|
||||
"collectionTitle": "A Night at the Opera",
|
||||
"creatorId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
|
||||
"creatorName": "Queen",
|
||||
"coverPath": "/media/music/Queen-3b3a19f3/A Night at the Opera-e8d52f7b/cover.jpg"
|
||||
},
|
||||
{
|
||||
"mediaKind": "Book",
|
||||
"mediaItemId": "4a5b6c7d-8e9f-4a0b-9c1d-2e3f4a5b6c7d",
|
||||
"isAvailable": true,
|
||||
"libraryId": "5c6d7e8f-9a0b-4c1d-8e2f-3a4b5c6d7e8f",
|
||||
"title": "The Hobbit",
|
||||
"collectionId": "00000000-0000-0000-0000-000000000000",
|
||||
"collectionTitle": "",
|
||||
"creatorId": "00000000-0000-0000-0000-000000000000",
|
||||
"creatorName": "J. R. R. Tolkien",
|
||||
"coverPath": null
|
||||
},
|
||||
{
|
||||
"mediaKind": "MusicAlbum",
|
||||
"mediaItemId": "0f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f",
|
||||
"isAvailable": false,
|
||||
"libraryId": "00000000-0000-0000-0000-000000000000",
|
||||
"title": "",
|
||||
"collectionId": "00000000-0000-0000-0000-000000000000",
|
||||
"collectionTitle": "",
|
||||
"creatorId": "00000000-0000-0000-0000-000000000000",
|
||||
"creatorName": "",
|
||||
"coverPath": null
|
||||
}
|
||||
],
|
||||
"currentPage": 1,
|
||||
"perPage": 200,
|
||||
"count": 3,
|
||||
"numberOfPages": 1
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `data` | The favorites of the page, from the most recently favorited. |
|
||||
| `currentPage` | The one based page number. |
|
||||
| `perPage` | The number of favorites per page. |
|
||||
| `count` | The number of favorites that match the `mediaKind` filter, even when only a page of them is returned. |
|
||||
| `numberOfPages` | The total number of pages. |
|
||||
|
||||
Each item carries the kind and Id of the favorited media item together with its display details. The display fields are generic across media kinds, and "no value" is the empty Guid or the empty string:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `mediaKind` | The kind of the favorited media item. |
|
||||
| `mediaItemId` | The Id of the favorited media item. |
|
||||
| `isAvailable` | Whether the item still exists and its library is accessible to the user. When it is `false`, every display field below is empty. |
|
||||
| `libraryId` | The Id of the library that contains the item. |
|
||||
| `title` | The title of the item. |
|
||||
| `collectionId`, `collectionTitle` | The Id and the title of the collection the item belongs to. |
|
||||
| `creatorId`, `creatorName` | The Id and the name of the creator of the item. |
|
||||
| `coverPath` | The stored path of the cover art of the item, the same kind of value the artist, album and book resources expose as `coverPath`, or `null` when it has none. The cover of a track is the cover of its album. |
|
||||
|
||||
How the generic fields map to each kind:
|
||||
|
||||
| Kind | `title` | `collection` | `creator` |
|
||||
| --- | --- | --- | --- |
|
||||
| `MusicArtist` | The artist name. | None. | None. |
|
||||
| `MusicAlbum` | The album title. | None. | The artist. |
|
||||
| `MusicTrack` | The track title. | The album. | The artist. |
|
||||
| `Book` | The book title. | None today: the series of a book is not catalogued yet, so the collection is always empty. | The first author, by display name. |
|
||||
|
||||
An item whose display details no longer exist, because the item was deleted, or whose library the current user cannot access, is returned with `isAvailable` set to `false` and every display field empty. It stays in `data` and in `count`, so its owner can see it and remove it with [Remove Favorite](#remove-favorite), and the response never exposes display data from a library the user cannot reach. The Id of the media item is the one the user favorited, and carries no information beyond that.
|
||||
|
||||
### Get Favorite Status
|
||||
|
||||
#### Get Favorite Status Request
|
||||
|
||||
```js
|
||||
GET api/v1/users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds=9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f&mediaItemIds=8e9f0a1b-2c3d-4e5f-9a6b-7c8d9e0f1a2b
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
| Query parameter | Type | Required | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `mediaKind` | string | yes | The kind of every media item checked: `MusicArtist`, `MusicAlbum`, `MusicTrack` or `Book`. |
|
||||
| `mediaItemIds` | Guid, repeated | yes | The Ids of the media items to check, one `mediaItemIds` parameter per Id, from 1 to 100. None can be the empty Guid. Repeated Ids are checked once. |
|
||||
|
||||
Tells which of the given media items are favorites of the current user. It reads only the favorites of the current user and evaluates no library access, so the answer reveals nothing about any other user, and an Id that is not a favorite, does not exist or belongs to an inaccessible library is simply absent from the answer. A page that renders many favorite toggles uses it to hydrate all of them with one request per kind.
|
||||
|
||||
#### Get Favorite Status Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"favoritedMediaItemIds": [
|
||||
"9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `favoritedMediaItemIds` | The Ids, among the checked ones, that the current user favorited. Empty when none is. |
|
||||
|
||||
### Media Kinds
|
||||
|
||||
The media kind is stored by its name, together with the Id of the item.
|
||||
|
||||
| Kind | Status | Item |
|
||||
| --- | --- | --- |
|
||||
| `MusicArtist` | Supported | An artist of a music library. |
|
||||
| `MusicAlbum` | Supported | An album of a music library. |
|
||||
| `MusicTrack` | Supported | A track of a music library. |
|
||||
| `Book` | Supported | A book of a book library. |
|
||||
| `Video` | Planned | A video file. Video libraries are not catalogued yet. |
|
||||
| `Photo` | Planned | A photo. Photo libraries are not catalogued yet. |
|
||||
|
||||
### Scoping and Library Access
|
||||
|
||||
Every operation is scoped to the current user by the server: the user is read from the authenticated principal, never from the route, the query or the body, so a user cannot read or change the favorites of another user.
|
||||
|
||||
Adding a favorite also applies the library access rule. The server resolves the library that contains the item, through the catalogue of its kind, and then evaluates the library ownership policy of the current user for that library, exactly as the library routes do. An item that does not exist, and an item whose library is not accessible to the current user, are both reported with the same kind specific not found error, so the response cannot be used to find out whether an item exists in a library of another user. The not found error depends on the kind:
|
||||
|
||||
| Kind | Not found error |
|
||||
| --- | --- |
|
||||
| `MusicArtist` | `ArtistNotFound` |
|
||||
| `MusicAlbum` | `AlbumNotFound` |
|
||||
| `MusicTrack` | `TrackNotFound` |
|
||||
| `Book` | `BookNotFound` |
|
||||
|
||||
Removing, and checking the status of, favorites do not evaluate the rule, because they only touch the favorites of the current user. Listing evaluates the rule once for each distinct library among the items of the page, and an item of an inaccessible library is returned as unavailable, as described in [Get Favorites Response](#get-favorites-response).
|
||||
|
||||
### Errors
|
||||
|
||||
Errors are returned as problem details. A request without a valid token is rejected with `401 Unauthorized` before it reaches the operation.
|
||||
|
||||
| Status | Error | When |
|
||||
| --- | --- | --- |
|
||||
| `401` | | The request carries no token, or an invalid or expired one. The body is a problem whose `title` is `Unauthorized` and whose `detail` says why, for example `The token has expired`. |
|
||||
| `403` | `NotAuthorized` | The authenticated principal carries no user identity. |
|
||||
| `404` | `ArtistNotFound` | [Add Favorite](#add-favorite) of a `MusicArtist` that does not exist or whose library the user cannot access. |
|
||||
| `404` | `AlbumNotFound` | [Add Favorite](#add-favorite) of a `MusicAlbum` that does not exist or whose library the user cannot access. |
|
||||
| `404` | `TrackNotFound` | [Add Favorite](#add-favorite) of a `MusicTrack` that does not exist or whose library the user cannot access. |
|
||||
| `404` | `BookNotFound` | [Add Favorite](#add-favorite) of a `Book` that does not exist or whose library the user cannot access. |
|
||||
| `409` | `ConcurrencyConflict` | The storage reported a busy or locked database while the change was saved. Repeating the request is safe. |
|
||||
| `422` | see below | The request failed validation. |
|
||||
|
||||
The `404` and `409` problems carry the generic error code in `title` and the specific name in `detail`:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "General.NotFound",
|
||||
"status": 404,
|
||||
"detail": "TrackNotFound",
|
||||
"instance": "/api/v1/users/me/favorites",
|
||||
"traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
|
||||
}
|
||||
```
|
||||
|
||||
A request that fails validation is rejected with `422 Unprocessable Entity` and a validation problem whose `errors` object lists the names of the validation errors under the generic `General.Validation` code:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "General.Validation",
|
||||
"status": 422,
|
||||
"detail": "OneOrMoreValidationErrorsOccurred",
|
||||
"instance": "/api/v1/users/me/favorites",
|
||||
"errors": {
|
||||
"General.Validation": [
|
||||
"FavoriteMediaKindIsNotSupported"
|
||||
]
|
||||
},
|
||||
"traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
|
||||
}
|
||||
```
|
||||
|
||||
The validation errors of each operation are:
|
||||
|
||||
| Error | Operation | When |
|
||||
| --- | --- | --- |
|
||||
| `FavoriteMediaKindIsInvalid` | Add, Remove, Get Favorites, Get Favorite Status | The kind is missing where it is required, or it is a number that is not a member of the media kind enumeration. In the Remove route, the segment is not a member name of the enumeration, and numbers are not accepted. |
|
||||
| `FavoriteMediaKindIsNotSupported` | Add | The kind is `Video` or `Photo`, which are planned and cannot be favorited yet. |
|
||||
| `FavoriteMediaItemIdCannotBeEmpty` | Add, Remove, Get Favorite Status | The item Id is missing or is the empty Guid. In the Remove route it is also reported when the segment is not a Guid. For the status request, any of the Ids is the empty Guid. |
|
||||
| `FavoriteMediaItemIdsCannotBeEmpty` | Get Favorite Status | No `mediaItemIds` were given. |
|
||||
| `FavoriteMediaItemIdsExceedMaximumCount` | Get Favorite Status | More than 100 Ids were given. |
|
||||
|
||||
A value that cannot be bound is not reported by the validators. This covers a `mediaKind` that is not a member of `FavoriteMediaKind` (for example `"Song"`, or a number outside the enumeration), an item Id that is not a Guid in the Add body or the status query, and a `currentPage` or `perPage` that is not an integer. The endpoints do not catch binding failures, so the request is answered by the exception handling middleware as a generic `500 Internal Server Error` problem, exactly like every other endpoint of the API that binds an enumeration or a number, and not with the `422` problem above. The web client never sends such values, because its proxy endpoints rebuild the query from typed values.
|
||||
|
||||
`FavoriteAlreadyExists` is defined among the favorites errors, but adding is idempotent, so no operation returns it. `FavoriteNotFound` remains defined for the storage read that follows an add, but removing is idempotent, so a remove request no longer returns it.
|
||||
|
||||
### Pagination Limits
|
||||
|
||||
| Limit | Value |
|
||||
| --- | --- |
|
||||
| Default per page of Get Favorites | 200 favorites, when a page is requested. |
|
||||
| Minimum per page of Get Favorites | 1 favorite. |
|
||||
| Maximum per page of Get Favorites | None. The server has no separate maximum page size, matching the other paginated collections of the API. |
|
||||
| Ids of one Get Favorite Status request | From 1 to 100, one kind per request. The Ids travel in the query string, so the limit keeps the request line under the 8 KB default of Kestrel. |
|
||||
|
||||
The limits bound a response or a request, not the number of favorites a user can have. A client that needs more than 100 Ids checked splits them into several requests, as the bundled web client does.
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# Architecture Decision Record (ADR): 0017 - One Generic Favorites Aggregate Keyed by Media Kind and Item Id
|
||||
|
||||
## Status
|
||||
|
||||
**Accepted** (2026-10-21)
|
||||
|
||||
## Context
|
||||
|
||||
A user must be able to mark any media item as a favorite: today the artists, albums and tracks of a music library and the books of a book library, and later videos and photos. Playlists already reference media items across bounded contexts by storing a media kind and a media item Id without a foreign key.
|
||||
|
||||
Favorites raise the same question with different constraints:
|
||||
|
||||
1. **One concept, many contexts**: a favorite is the same fact for every media kind, so a table and an aggregate per media kind would repeat one model four times now, and again for every media kind that is added.
|
||||
2. **Bounded context isolation**: as specified by DDD, an aggregate does not reference objects of another bounded context, only identifiers placed in `ExternalIdentifiers` directories. A favorites aggregate that held an `Artist`, a `Book` or any other media entity would couple favorites to every media context.
|
||||
3. **Referential integrity across kinds**: one table cannot declare a foreign key to the tables of several media kinds. A favorite must also outlive the item it references, because a library scan or a manual delete can remove an item, and the owner of the favorite has to be able to see and remove it afterwards instead of the favorite silently disappearing.
|
||||
4. **Concurrent toggles**: a favorite toggle is rendered on many pages, and a user can have several tabs open, so the same add can arrive twice at nearly the same moment.
|
||||
5. **Access control**: favoriting an item must not reveal whether an item exists in a library the user cannot access, and listing must not expose the display data of such a library.
|
||||
|
||||
## Decision
|
||||
|
||||
Store favorites as one generic `Favorite` aggregate in `FavoriteBoundedContext`, in one `Favorites` table. The table has a surrogate `FavoriteId` primary key and a unique business key `(UserId, MediaKind, MediaItemId)`. A media item is referenced only by its `FavoriteMediaKind` and the external `MediaItemId`; there is no foreign key to a media table. There are no per-kind favorite aggregates, tables, endpoints or contracts.
|
||||
|
||||
The decision includes these rules:
|
||||
|
||||
- **Add is idempotent.** Adding an item the user already favorited returns the existing favorite and raises no event.
|
||||
- **Remove is idempotent.** Removing a favorite that is already absent succeeds without changing anything and raises no event.
|
||||
- **The owner always comes from the authenticated principal.** No route, query or body carries the owner, and no administrator or library-owner override exposes another user's favorites.
|
||||
- **Access is checked where it can leak.** Adding evaluates the library ownership policy of the item's library. Listing evaluates it for each distinct library in the returned page and hides the display data of inaccessible libraries. Removing and checking the status read only the current user's own favorites, so they evaluate no library policy.
|
||||
- **Dangling favorites stay visible.** A favorite whose item no longer exists, or whose library is no longer accessible, is returned as an unavailable item with empty display fields so its owner can see and remove it.
|
||||
- **Reads use the shared pagination contract.** The repository accepts the shared `PaginationDataDto` and returns the shared `PaginatedResultDto<T>`, like every other paginated listing. When the request provides neither `currentPage` nor `perPage`, every matching favorite is returned in a single page; when a page is requested, the page defaults to `1` and the page size defaults to `200`. A page beyond the last one is clamped to the last page, and there is no separate maximum page size. The status check accepts 1 to 100 Ids of one kind per request.
|
||||
|
||||
### Model
|
||||
|
||||
| Element | Decision |
|
||||
|---|---|
|
||||
| Aggregate | `Favorite` is the root, with a `FavoriteId`, a `UserId`, a `MediaItemId`, a `FavoriteMediaKind` and the audit columns. It has no entities. The user and the media item are referenced only through the identifier types in the context's `ExternalIdentifiers` directories; the kind is the shared `FavoriteMediaKind` enumeration. The media item identifier is generic across artists, albums, tracks, books and the planned video and photo kinds. |
|
||||
| Media kind | `FavoriteMediaKind` has `MusicArtist`, `MusicAlbum`, `MusicTrack`, `Book`, `Video` and `Photo`, and it is stored by name. `Favorite.IsSupported` is `true` for the first four, and creating a favorite of the planned `Video` and `Photo` kinds is rejected with the validation error `FavoriteMediaKindIsNotSupported`. A planned kind becomes supported by lifting the restriction, with no change to the storage schema. |
|
||||
| Domain events | `FavoriteAdded` is raised when a favorite is created, and `FavoriteRemoved` when it is removed. |
|
||||
| Storage | The `Favorites` table holds the Id, the owner, the media kind, the media item Id and the audit columns. The owner is a foreign key that cascades, so favorites leave with their user. The media item is not a foreign key. |
|
||||
| Invariant | A unique index on `(UserId, MediaKind, MediaItemId)` makes the storage medium the owner of the rule "one favorite per user and item", and serves the status check that looks up a user's favorites among checked Ids. Indexes on `(UserId, CreatedOnUtc)` and `(UserId, MediaKind, CreatedOnUtc)` serve the listing of every kind and of one kind. |
|
||||
| Display data | The repository resolves, per kind and with projections that do not materialize the entities, the library Id of an item and the generic display fields of a page of favorites. The display fields are the title, the collection Id and title, the creator Id and name, and the cover path. Each kind fills what it has, and "no value" is the empty Guid or the empty string. Adding a media kind adds one branch to each resolution and one entry to the enumeration, with no new table, endpoint or contract. |
|
||||
|
||||
### Operations
|
||||
|
||||
- **Add**: the handler validates, requires the current user, rejects an unsupported kind, resolves the library of the item, evaluates the library ownership policy and returns the existing favorite without an event when the user already favorited the item. Otherwise it creates the aggregate, inserts it, saves the unit of work, queues the aggregate's events and reads the row back. If the unique index rejects a concurrent add, the handler re-reads the existing favorite and returns it without an event.
|
||||
- **Remove**: the handler validates, requires the current user and loads the favorite by user, kind and item. A missing favorite is a successful removal with no event. Otherwise it removes the aggregate, deletes the row, saves the unit of work and queues the removal event. A concurrent removal is treated as success; any other concurrency conflict is reported.
|
||||
- **List**: the repository scopes the query to the current user inside the storage query and returns the paginated listing ordered by the time of favoriting, with the shared pagination metadata. The handler evaluates the library policy once per distinct library in the page and maps a favorite with missing or inaccessible display data to an unavailable item with empty display fields.
|
||||
- **Status**: the repository scopes the check to the current user and returns the Ids, among the checked ones, that the user favorited. The response carries only those Ids.
|
||||
- **Errors**: `FavoriteAlreadyExists` remains defined but no operation produces it. `FavoriteNotFound` is used only where a stored favorite cannot be read back; removal of an absent favorite succeeds. `FavoriteMediaKindIsNotSupported` is returned by Add for the planned kinds.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Outcomes
|
||||
|
||||
| Aspect | Benefit |
|
||||
|---|---|
|
||||
| One model | Multiple media kinds share one aggregate, one table, four operations and one set of contracts |
|
||||
| Context isolation | The aggregate holds identifiers only, so favorites depend on no media bounded context and could move to their own service |
|
||||
| Survives deletion | A favorite is not removed by deleting or rescanning its item, and its owner is shown an unavailable item that can be removed |
|
||||
| Race safe | The storage unique index, not the existence check alone, guarantees a single favorite per user and item, and a concurrent duplicate add resolves to the existing favorite |
|
||||
| No existence oracle | An inaccessible item and a missing item are indistinguishable when adding, and inaccessible display data is never listed |
|
||||
| No schema change for new kinds | The kind is stored by name, so a planned kind only needs its restriction lifted and its two resolutions written |
|
||||
|
||||
### Risks and Mitigations
|
||||
|
||||
| Risk | Mitigation Strategy |
|
||||
|---|---|
|
||||
| Without a foreign key, rows can point at items that no longer exist | This is intended: the listing returns such rows as unavailable and removal never needs the item. Nothing relies on the item being present |
|
||||
| The per-kind resolution is a switch in the repository, so a new kind could be added to the enumeration without a resolution | `GetMediaItemLibraryIdAsync` reports no library for a kind without a branch, so an add of it is reported as not found, and `Favorite.IsSupported` has to be extended together with the branch |
|
||||
| The listing evaluates the library policy once per distinct library of a page | The policy is evaluated once per distinct library, not once per favorite, so the cost grows with the number of distinct libraries rather than with the number of favorites. A client that needs a bound requests a page size, like every other paginated listing |
|
||||
| The display projections can drift from how the catalogues show their items | The projections reuse the same sources as the listings of each catalogue, so a change to how a catalogue shows an item has to be mirrored in the matching branch |
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### 1. One favorites table and aggregate per media kind
|
||||
|
||||
A `FavoriteArtist`, `FavoriteAlbum`, `FavoriteTrack` and `FavoriteBook` aggregate, each with a real foreign key to its media table.
|
||||
|
||||
**Rejected**: it repeats the same model, endpoints and contracts per kind, and again for every planned kind. The foreign keys would also make the favorite die with its item, which removes the user's ability to see and remove it, and each aggregate would need to reference a media bounded context directly.
|
||||
|
||||
### 2. A flag on each media entity
|
||||
|
||||
An `IsFavorite` column on artists, albums, tracks and books.
|
||||
|
||||
**Rejected**: a favorite is private to a user, and a flag on a shared catalogue row cannot be. A join table per user would be needed anyway, which brings back the first alternative.
|
||||
|
||||
### 3. Reuse the playlist model with a system playlist
|
||||
|
||||
Store favorites as the entries of a special playlist per user.
|
||||
|
||||
**Rejected**: a playlist is an ordered list that allows duplicates and is positioned by the user, while a favorite is an unordered set with exactly one entry per item and a listing ordered by the time of favoriting. The playlist operations, the position keys and the entry limits do not apply, and the favorites of artists, albums and books are not playable entries.
|
||||
|
||||
### 4. Enforce uniqueness only in the handler
|
||||
|
||||
Check for an existing favorite and rely on it, with no unique index.
|
||||
|
||||
**Rejected**: two requests of the same user can both pass the check, so duplicates would be created under concurrency. The storage medium must own the invariant, and the handler's check is kept only to make the common repeated add idempotent without a failure.
|
||||
|
||||
### 5. Return a conflict when an item is already a favorite
|
||||
|
||||
Report `FavoriteAlreadyExists` instead of returning the existing favorite.
|
||||
|
||||
**Rejected**: a toggle rendered on several pages, and several open tabs, make a repeated add a normal event rather than an error. An idempotent add keeps the client simple, since it does not have to distinguish a created favorite from an existing one. `FavoriteAlreadyExists` remains defined in the favorites error set, but no operation produces it.
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
- _**Metadata**_: Information describing a media item
|
||||
- _**User**_: A person who interacts with the media library
|
||||
- _**Playlist**_: A curated list of media items, potentially cross-media-type
|
||||
- _**Favorite**_: The marker a user places on a media item of any media kind, private to that user. It references the item only by its kind and its Id, so one concept serves music, books and the media kinds that are planned
|
||||
- _**FavoriteMediaKind**_: The set of media item kinds that can be marked as a favorite
|
||||
- _**Tag**_: A label for categorizing and organizing media items
|
||||
- _**Collection**_: A user-defined group of any media items
|
||||
- _**File**_: The actual digital file of a media item
|
||||
@@ -95,6 +97,7 @@
|
||||
- PhotoAlbum
|
||||
- User
|
||||
- Playlist
|
||||
- Favorite
|
||||
- Collection
|
||||
- SubtitleFile
|
||||
- Lyrics
|
||||
@@ -114,6 +117,7 @@
|
||||
- PhotoLibrary (root: PhotoLibrary, entities: Photo, PhotoAlbum, AlbumArtwork, MoviePoster)
|
||||
- UserProfile (root: User, entities: Collection)
|
||||
- PlaylistManagement (root: Playlist, entities: PlaylistEntry)
|
||||
- Favorites (root: Favorite, no entities)
|
||||
- SupplementaryContentLibrary (root: SupplementaryContentLibrary, entities: SubtitleFile, Lyrics, LanguageTrack)
|
||||
- FileSystemManagement (root: File, entities: Stream)
|
||||
|
||||
@@ -213,6 +217,8 @@
|
||||
- PlaylistEntryRemoved
|
||||
- PlaylistEntriesReordered
|
||||
- PlaylistDeleted
|
||||
- FavoriteAdded
|
||||
- FavoriteRemoved
|
||||
- UserPreferencesChanged
|
||||
- MetadataUpdated
|
||||
- FileTranscoded
|
||||
@@ -229,6 +235,8 @@
|
||||
- Services: RecommendationEngine, ContentCurationService, UserActivityTrackingService
|
||||
- PlaylistManagement
|
||||
- Aggregates: Playlist
|
||||
- Favorites
|
||||
- Aggregates: Favorite
|
||||
- ContentDelivery
|
||||
- Aggregates: FileSystemManagement
|
||||
- Services: StreamingService, ContentSynchronizationService
|
||||
@@ -244,6 +252,7 @@
|
||||
- PhotoRepository
|
||||
- UserRepository
|
||||
- PlaylistRepository
|
||||
- FavoriteRepository
|
||||
- CollectionRepository
|
||||
- FileRepository
|
||||
- StreamRepository
|
||||
@@ -0,0 +1,8 @@
|
||||
POST {{host}}/api/v1/users/me/favorites
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"mediaKind": "MusicTrack",
|
||||
"mediaItemId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/users/me/favorites/status?mediaKind=MusicTrack&mediaItemIds=9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f&mediaItemIds=8e9f0a1b-2c3d-4e5f-9a6b-7c8d9e0f1a2b
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/users/me/favorites?mediaKind=MusicTrack¤tPage=1&perPage=200
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,2 @@
|
||||
DELETE {{host}}/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -19,6 +19,11 @@ The web client of Lumina is a themed shell: every page is rendered inside the te
|
||||
- [The audio player sub templates](#the-audio-player-sub-templates)
|
||||
- [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu)
|
||||
- [Page Templates](#page-templates)
|
||||
- [The Playlist Pages](#the-playlist-pages)
|
||||
- [The Shared Add to Playlist Action](#the-shared-add-to-playlist-action)
|
||||
- [The Album Track Actions Menu](#the-album-track-actions-menu)
|
||||
- [The Favorites Page](#the-favorites-page)
|
||||
- [Favorite Toggles](#favorite-toggles)
|
||||
- [The Scripts Section](#the-scripts-section)
|
||||
- [Assets](#assets)
|
||||
- [Configuration Options](#configuration-options)
|
||||
@@ -171,6 +176,7 @@ Known page keys:
|
||||
| `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. |
|
||||
| `favorites/index` | The page that lists, filters and removes the favorites of the current user across media kinds. |
|
||||
| `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. |
|
||||
@@ -523,11 +529,11 @@ Page templates are rendered into a content section that the layout wraps. A page
|
||||
| --- | --- |
|
||||
| `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. |
|
||||
| `playlistJson` | The playlist metadata and only the first page of its ordered entries, serialized as JSON. `entries.count` is the total number of entries, and `entries.currentPage`, `entries.perPage` and `entries.numberOfPages` describe the page. 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. |
|
||||
| `entriesPerPage` | The number of entries per page the page requests. The page fetches the next pages 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. |
|
||||
| `getPlaylistUrl` | The route that returns a page of the playlist. It takes `currentPage` and `perPage` query parameters and returns `entries` with `data`, `currentPage`, `perPage`, `count` and `numberOfPages`. When both pagination parameters are omitted, every entry is returned in one page. The `perPage` is the page size the theme requests. |
|
||||
| `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. |
|
||||
@@ -543,7 +549,7 @@ Page templates are rendered into a content section that the layout wraps. A page
|
||||
|
||||
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 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 page 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.
|
||||
|
||||
@@ -569,6 +575,82 @@ The player queue action does not use `addToPlaylistLabel`. Its label comes from
|
||||
|
||||
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 Favorites Page
|
||||
|
||||
`favorites/index` receives a model with the following fields:
|
||||
|
||||
| Field | Content |
|
||||
| --- | --- |
|
||||
| `getFavoritesUrl` | The route that returns a page of the favorites of the current user. It takes the optional `mediaKind`, `currentPage` and `perPage` query parameters, and returns `data`, `currentPage`, `perPage`, `count` and `numberOfPages`. When both pagination parameters are omitted, every matching favorite is returned in one page. The `perPage` is the page size the theme requests; the server has no separate maximum page size, like every other paginated collection of the API. |
|
||||
| `getFavoriteStatusUrl` | The route that tells which of a list of media items of one kind are favorites of the current user. It takes the `mediaKind` query parameter and one `mediaItemIds` parameter per Id, with at most 100 Ids. |
|
||||
| `addFavoriteUrl` | The route that marks a media item as a favorite. The body carries `mediaKind` and `mediaItemId`. |
|
||||
| `removeFavoriteUrl` | The route template that removes a favorite. Its named `{mediaKind}` and `{mediaItemId}` placeholders are replaced by the media kind name and the Id of the media item. |
|
||||
| `artistUrl` | The route template of an artist page. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the artist. |
|
||||
| `albumUrl` | The route template of an album page. The two `00000000-0000-0000-0000-000000000000` segments are replaced, in order, by the Ids of the artist and the album. |
|
||||
| `trackUrl` | The route template of a track page. The three `00000000-0000-0000-0000-000000000000` segments are replaced, in order, by the Ids of the artist, the album and the track. |
|
||||
| `bookUrl` | The route template of a book page. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. |
|
||||
| `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 pages of the media items read the library of the item from the `libraryId` query parameter, so the page script appends `libraryId` to the link of an item from the `libraryId` of the favorite. The link of a track needs the artist and the album of the item, which are the `creatorId` and the `collectionId` of the favorite. An item of the response with `isAvailable` set to `false` has no library and no display fields, so the page shows it as an unavailable item, without a link, and keeps its heart so the favorite can still be removed. The generic display fields of an item are `title`, `collectionTitle`, `creatorName` and `coverPath`; for a track the collection is the album and the creator is the artist, for an album the creator is the artist, for a book the creator is its first author, and for an artist there is neither. The series of a book is not catalogued yet, so a book has no collection.
|
||||
|
||||
The fallback view keeps these element hooks, which the application script drives: `favorites-container`, `no-favorites`, `favorite-count`, `favorites-kind-filter`, `load-more-favorites-button` and `retry-favorites-button`. The bundled themes ship no template for `favorites/index`, so the fallback view is what a healthy site shows, and a theme that wants its own page provides `templates/favorites/index.html` and must keep the hooks the page script needs.
|
||||
|
||||
The fallback view renders one card per favorite, from the most recently favorited, in pages of 50 that `load-more-favorites-button` extends. Each card carries a favorite heart (a `card-favorite-toggle` button, described below), already in the favorited state, and a favorite is removed from the page by unfavoriting its card: the page script does not call the remove route itself, the global favorites script does, and the page listens to the `lumina:favorite-changed` event described below, removes the card of an item that is no longer a favorite, and updates the counter and the empty state without another request. A failed first page or reload clears the rendered cards and shows the localized failure message with `retry-favorites-button`, so the user can load the current filter again instead of being left with a truncated list. A theme template that renders the page itself gets the same behavior by rendering hearts on its cards and handling that event.
|
||||
|
||||
#### Favorite Toggles
|
||||
|
||||
A favorite toggle is the heart of a media card or of a track row. It is rendered by a page or by a theme template, and it is driven entirely by the global script `wwwroot/js/favorites.js`, which every layout loads next to `playlists.js`. The script binds one click listener and one mutation observer on the document, so a toggle works anywhere in the swapped page content, including toggles that a page script adds later, and a page needs no script of its own. A theme owns the look of the toggle, and the script never renders markup: it only writes the attributes, the class and the texts described below.
|
||||
|
||||
A toggle is any focusable element, normally a `button`, that carries these attributes:
|
||||
|
||||
| Attribute | Meaning |
|
||||
| --- | --- |
|
||||
| `data-favorite-toggle` | Required. Marks the element as a favorite toggle. |
|
||||
| `data-favorite-media-kind` | Required. The media kind of the item: `MusicArtist`, `MusicAlbum`, `MusicTrack` or `Book`. The name is matched case insensitively. The planned kinds `Video` and `Photo` cannot be favorited yet, so a toggle that carries one stays in the `failed` state. |
|
||||
| `data-favorite-media-item-id` | Required. The Id of the media item. An empty or malformed Id leaves the toggle in the `failed` state. |
|
||||
|
||||
The script reads which items the current user favorited with `getFavoriteStatusUrl` and writes the result on the toggle. It collects the toggles of a tick and sends one status request per kind, deduplicates the Ids, and splits the Ids of a kind into requests of at most 100, so a page that renders many toggles costs few requests. The script writes these on the element:
|
||||
|
||||
| Written on the toggle | Meaning |
|
||||
| --- | --- |
|
||||
| `aria-pressed` | `true` when the item is a favorite, `false` otherwise. It keeps the previous value while a request is in flight. |
|
||||
| `data-favorite-state` | `favorited` or `not-favorited` when the state is known, `loading` while the state is read or a change is in flight, and `failed` when the state could not be read or the attributes are invalid. |
|
||||
| `is-favorite` class | Present exactly when the item is a favorite. |
|
||||
| `aria-busy` | `true` only while the state is loading or a change is in flight. |
|
||||
| `aria-label` | The localized name of the action the next click performs: the `remove` string when the item is a favorite, the `add` string otherwise. |
|
||||
| `title` | The same localized text as the `aria-label`. It is the hover text of a heart, which has no visible text. |
|
||||
| The text of `.favorite-toggle-label` | When the toggle contains an element with the `favorite-toggle-label` class, the same localized text as the `aria-label`. The bundled themes and the application views render no such element. |
|
||||
|
||||
A theme restyles a toggle from the `is-favorite` class or from the `aria-pressed` and `data-favorite-state` attributes. Until the first state arrives the toggle shows `loading`, so a theme should not style a toggle that has no state yet as pressed.
|
||||
|
||||
A click on a toggle adds the favorite when the item is not one, and removes it otherwise, through the add and remove routes of the configuration. A click is ignored while a request for the same item is in flight, whichever toggle of the item it comes from, and a click on a toggle whose state is unknown reads the state again instead of guessing. The script keeps every toggle of the same item on the page in sync. When a change fails, every toggle returns to the state it had, and the global API helper shows the failure as a notification. When a state read fails, the global API helper shows the failure as a notification. The click handler prevents the default action, so a toggle inside a link or a card does not also navigate.
|
||||
|
||||
After every successful change the script dispatches the `lumina:favorite-changed` event on `document`, with `detail` carrying `mediaKind` (the canonical kind name), `mediaItemId` (the lowercase Id) and `isFavorite` (the new state), so a page that lists favorites can react while it stays decoupled from the toggle that caused the change.
|
||||
|
||||
The layout provides the shared configuration as `window.favoritesConfiguration`:
|
||||
|
||||
| Field | Content |
|
||||
| --- | --- |
|
||||
| `getFavoriteStatusUrl` | The route that tells which of the checked media items are favorites. |
|
||||
| `addFavoriteUrl` | The route that marks a media item as a favorite. The body carries `mediaKind` and `mediaItemId`. |
|
||||
| `removeFavoriteUrlTemplate` | The route template that removes a favorite. Its named `{mediaKind}` and `{mediaItemId}` placeholders are replaced by the media kind name and the Id of the media item. |
|
||||
| `strings` | The localized labels: `add` and `remove`. |
|
||||
|
||||
The script also exposes `window.LuminaFavorites` for page scripts that need more than the markup contract:
|
||||
|
||||
| Member | Behavior |
|
||||
| --- | --- |
|
||||
| `hydrate(rootElement)` | Reads the state of the toggles inside the element, the whole document by default, and writes it on them. It never rejects. The script already hydrates the toggles of the page and the ones added to it, so this is only needed for toggles in an element that is not attached to the document. |
|
||||
| `isFavorite(mediaKind, mediaItemId)` | Returns a promise of whether the item is a favorite. The answer always comes from the server, and the check is batched with the others of the same tick. It rejects when the kind or the Id is invalid, or when the request failed. |
|
||||
| `setFavoriteAsync(mediaKind, mediaItemId, shouldFavorite)` | Adds or removes the favorite, with the same in-flight rule, synchronization and failure notification from the global API helper as a click, and returns a promise of whether the item now has the requested state. A call for an item that is already being changed returns the running change when it asks for the same state, and `false` otherwise. |
|
||||
|
||||
The hearts are rendered on the cards of the books list, of the artists list and of the albums on the artist page (the kinds `Book`, `MusicArtist` and `MusicAlbum`), on the cards of the favorites page, and on the rows of the track table of the album page (the kind `MusicTrack`, after the duration). The detail pages of an artist, an album, a track and a book render no toggle. The audio player bar and the playlist rows have none either, so a theme should not assume they exist.
|
||||
|
||||
A card heart is a plain `button` with the `card-favorite-toggle` class, with the three data attributes and nothing else, appended to the `media-card` element as a sibling of the `media-panel` link and of the `card-actions-trigger`. The stylesheet draws the heart with `::after`, like the dots of the actions trigger. The heart has the box of the actions trigger, sits immediately on its left, is shown on hover, while the actions menu of the card is open, and while any control of the card has the focus, shows the heart in the blue of the trigger, and shows it in red when the item is a favorite (`aria-pressed="true"` or the `is-favorite` class). A heart in the `loading` state is dimmed, and one in the `failed` state has an error border. A `media-card` that has no `card-actions-trigger`, like the cards of the favorites page, gets the heart in the place of the trigger, always visible so that it stays reachable by keyboard and on touch screens. A track row heart is a `button` with the `card-favorite-toggle track-favorite-toggle` classes inside a `td` with the `track-favorite-cell` class that follows the duration cell, and the `colgroup` of the table gets a `col` with the `track-favorite-column` class after the duration column. It is static, always visible and centered, like the actions trigger of the row. The hover text of every heart is the `title` that the script writes.
|
||||
|
||||
The bundled themes render the hearts on those cards and rows, and carry the card rules in their `assets/site.css`; the rules of the track row and of its columns are in the application stylesheet, `wwwroot/css/site.css`, which every page loads. The application fallback views render the same hearts. A custom theme that replaces one of these templates must render the hearts again to keep favoriting reachable from that page.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the generic display data of a favorited media item.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For a music artist the title is the artist name and there is no collection or creator. For a music album the title is the album title,
|
||||
/// there is no collection, and the creator is the artist. For a music track the title is the track title, the collection is the album and
|
||||
/// the creator is the artist. For a book the title is the book title, there is no collection yet because the series of a book is not catalogued, and the creator is its
|
||||
/// first author.
|
||||
/// </remarks>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
|
||||
/// <param name="Title">The title of the media item.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
|
||||
[DebuggerDisplay("LibraryId: {LibraryId}; Title: {Title}")]
|
||||
public sealed record FavoriteItemDisplayDto(
|
||||
Guid LibraryId,
|
||||
string Title,
|
||||
Guid CollectionId,
|
||||
string CollectionTitle,
|
||||
Guid CreatorId,
|
||||
string CreatorName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a stored favorite together with the display data of the media item it references.
|
||||
/// </summary>
|
||||
/// <param name="Favorite">The stored favorite.</param>
|
||||
/// <param name="Display">The display data of the referenced media item, or <see langword="null"/> when it no longer exists.</param>
|
||||
[DebuggerDisplay("Id: {Favorite.Id}; MediaKind: {Favorite.MediaKind}")]
|
||||
public sealed record FavoriteItemDto(
|
||||
FavoriteEntity Favorite,
|
||||
FavoriteItemDisplayDto? Display
|
||||
);
|
||||
@@ -1,16 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using System.Collections.Generic;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// A stored playlist together with a window of its entries and their display data.
|
||||
/// Data transfer object for a stored playlist together with a page of its entries and their display data.
|
||||
/// </summary>
|
||||
/// <param name="Playlist">The stored playlist.</param>
|
||||
/// <param name="Entries">The requested window of entries.</param>
|
||||
/// <param name="Entries">The requested page of entries.</param>
|
||||
[DebuggerDisplay("PlaylistId: {Playlist.Id}; Name: {Playlist.Name}; Entries: {Entries.Count}")]
|
||||
public sealed record PlaylistDetailsDto(
|
||||
PlaylistEntity Playlist,
|
||||
IReadOnlyList<PlaylistEntryDto> Entries
|
||||
PaginatedResultDto<PlaylistEntryDto> Entries
|
||||
);
|
||||
@@ -1,11 +1,12 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#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.
|
||||
/// Data transfer object for the 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>
|
||||
@@ -16,6 +17,7 @@ namespace Lumina.Application.Common.DTO.Playlists;
|
||||
/// <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>
|
||||
[DebuggerDisplay("TrackId: {TrackId}; TrackTitle: {TrackTitle}")]
|
||||
public sealed record PlaylistEntryDisplayDto(
|
||||
Guid TrackId,
|
||||
string TrackTitle,
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using System.Diagnostics;
|
||||
#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.
|
||||
/// Data transfer object for 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>
|
||||
[DebuggerDisplay("EntryId: {Entry.Id}; MediaItemId: {Entry.MediaItemId}; Position: {DisplayPosition}")]
|
||||
public sealed record PlaylistEntryDto(
|
||||
PlaylistEntryEntity Entry,
|
||||
PlaylistEntryDisplayDto? Display,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.Playlists;
|
||||
@@ -15,6 +16,7 @@ namespace Lumina.Application.Common.DTO.Playlists;
|
||||
/// <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 PlaylistSummaryDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a favorite - the marker of a user on a media item of any media kind.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The favorite references the media item by its kind and its Id, without a foreign key, so the same table serves every media context and a
|
||||
/// favorite survives the deletion of the item it references, so its owner can still see and remove it.
|
||||
/// </remarks>
|
||||
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public class FavoriteEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the favorite.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that owns the favorite.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the kind of the favorited media item.
|
||||
/// </summary>
|
||||
public required FavoriteMediaKind MediaKind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the favorited media item.
|
||||
/// </summary>
|
||||
public required Guid MediaItemId { 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; }
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for favorites.
|
||||
/// </summary>
|
||||
public interface IFavoriteRepository : IRepository<FavoriteEntity>,
|
||||
IInsertRepositoryAction<FavoriteEntity>,
|
||||
IDeleteByIdRepositoryAction<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the favorite of the user identified by <paramref name="userId"/> on the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the favorite must belong to.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entity should be tracked by the persistence medium, so that changes to it 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 favorite, <see langword="null"/> when the user has not favorited the media item, or an error.
|
||||
/// </returns>
|
||||
Task<Result<FavoriteEntity?>> GetByMediaItemIdForUserAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library that contains the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if the media item exists.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the Id of the library that contains the media item, <see langword="null"/> when the
|
||||
/// media item does not exist or its kind has no catalogued library yet, or an error.
|
||||
/// </returns>
|
||||
Task<Result<Guid?>> GetMediaItemLibraryIdAsync(FavoriteMediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the paginated favorites of the user identified by <paramref name="userId"/>, together with the display data of the media items they reference,
|
||||
/// or all the matching favorites when the pagination data is <see langword="null"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are retrieved.</param>
|
||||
/// <param name="mediaKind">The kind of media item to restrict the favorites to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching favorites are returned.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{FavoriteItemDto}"/>, or an error.</returns>
|
||||
Task<Result<PaginatedResultDto<FavoriteItemDto>>> GetAllForUserAsync(Guid userId, FavoriteMediaKind? mediaKind, PaginationDataDto? paginationData = null, bool shouldTrackEntities = false, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Ids, among <paramref name="mediaItemIds"/>, of the media items of kind <paramref name="mediaKind"/> that the user identified by <paramref name="userId"/> has favorited.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are checked.</param>
|
||||
/// <param name="mediaKind">The kind of the media items.</param>
|
||||
/// <param name="mediaItemIds">The Ids of the media items to check.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the subset of the Ids that are favorites of the user, or an error.</returns>
|
||||
Task<Result<IReadOnlyList<Guid>>> GetFavoritedMediaItemIdsForUserAsync(Guid userId, FavoriteMediaKind mediaKind, IReadOnlyCollection<Guid> mediaItemIds, CancellationToken cancellationToken);
|
||||
}
|
||||
+5
-3
@@ -2,6 +2,7 @@
|
||||
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.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
@@ -44,16 +45,17 @@ public interface IPlaylistRepository : IRepository<PlaylistEntity>,
|
||||
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"/>.
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with a page of the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>, or all the entries when the pagination data is <see langword="null"/>.
|
||||
/// </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="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching entries are returned.</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);
|
||||
Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, PaginationDataDto? paginationData = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
@@ -161,6 +162,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IPlaylistRepository PlaylistRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite repository.
|
||||
/// </summary>
|
||||
IFavoriteRepository FavoriteRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="AddFavoriteRequest"/>.
|
||||
/// </summary>
|
||||
public static class AddFavoriteRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="AddFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static AddFavoriteCommand ToCommand(this AddFavoriteRequest request)
|
||||
{
|
||||
return new AddFavoriteCommand(request.MediaKind, request.MediaItemId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="FavoriteEntity"/>.
|
||||
/// </summary>
|
||||
public static class FavoriteEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="Favorite"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="Favorite"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Favorite> ToDomainEntity(this FavoriteEntity repositoryEntity)
|
||||
{
|
||||
return Favorite.Create(
|
||||
FavoriteId.Create(repositoryEntity.Id),
|
||||
UserId.Create(repositoryEntity.UserId),
|
||||
MediaItemId.Create(repositoryEntity.MediaItemId),
|
||||
repositoryEntity.MediaKind,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="FavoriteResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static FavoriteResponse ToResponse(this FavoriteEntity repositoryEntity)
|
||||
{
|
||||
return new FavoriteResponse(
|
||||
repositoryEntity.Id,
|
||||
repositoryEntity.MediaKind,
|
||||
repositoryEntity.MediaItemId,
|
||||
repositoryEntity.CreatedOnUtc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="FavoriteItemDto"/>.
|
||||
/// </summary>
|
||||
public static class FavoriteItemDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="FavoriteItemResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The favorite data to be converted.</param>
|
||||
/// <returns>The converted response, flagged as not available with empty display fields when the display data is missing.</returns>
|
||||
public static FavoriteItemResponse ToResponse(this FavoriteItemDto data)
|
||||
{
|
||||
if (data.Display is null)
|
||||
return new FavoriteItemResponse(
|
||||
data.Favorite.MediaKind,
|
||||
data.Favorite.MediaItemId,
|
||||
false,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
Guid.Empty,
|
||||
string.Empty,
|
||||
null);
|
||||
|
||||
FavoriteItemDisplayDto display = data.Display;
|
||||
return new FavoriteItemResponse(
|
||||
data.Favorite.MediaKind,
|
||||
data.Favorite.MediaItemId,
|
||||
true,
|
||||
display.LibraryId,
|
||||
display.Title,
|
||||
display.CollectionId,
|
||||
display.CollectionTitle,
|
||||
display.CreatorId,
|
||||
display.CreatorName,
|
||||
display.CoverPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to a paginated collection of <see cref="FavoriteItemResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The paginated favorite data to be converted.</param>
|
||||
/// <returns>The converted paginated responses.</returns>
|
||||
public static PaginatedResponse<FavoriteItemResponse> ToResponses(this PaginatedResultDto<FavoriteItemDto> data)
|
||||
{
|
||||
return new PaginatedResponse<FavoriteItemResponse>
|
||||
{
|
||||
Data = [.. data.Data.Select(item => item.ToResponse())],
|
||||
CurrentPage = data.CurrentPage,
|
||||
PerPage = data.PerPage,
|
||||
Count = data.Count,
|
||||
NumberOfPages = data.NumberOfPages
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="Favorite"/>.
|
||||
/// </summary>
|
||||
public static class FavoriteMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="FavoriteEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
public static FavoriteEntity ToRepositoryEntity(this Favorite domainEntity)
|
||||
{
|
||||
return new FavoriteEntity
|
||||
{
|
||||
Id = domainEntity.Id.Value,
|
||||
UserId = domainEntity.UserId.Value,
|
||||
MediaKind = domainEntity.MediaKind,
|
||||
MediaItemId = domainEntity.MediaItemId.Value,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc.Value : null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetFavoriteStatusRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetFavoriteStatusRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetFavoriteStatusQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetFavoriteStatusQuery ToQuery(this GetFavoriteStatusRequest request)
|
||||
{
|
||||
return new GetFavoriteStatusQuery(request.MediaKind, request.MediaItemIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetFavoritesRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetFavoritesRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetFavoritesQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetFavoritesQuery ToQuery(this GetFavoritesRequest request)
|
||||
{
|
||||
PaginationDataDto? paginationData = null;
|
||||
if (request.CurrentPage is not null || request.PerPage is not null)
|
||||
paginationData = new PaginationDataDto
|
||||
{
|
||||
CurrentPage = request.CurrentPage ?? 1,
|
||||
PerPage = request.PerPage ?? 200
|
||||
};
|
||||
|
||||
return new GetFavoritesQuery(
|
||||
request.MediaKind,
|
||||
paginationData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetPlaylistRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetPlaylistRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetPlaylistQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playlistId">The Id of the playlist whose entries are retrieved, taken from the route.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetPlaylistQuery ToQuery(this GetPlaylistRequest request, string? playlistId)
|
||||
{
|
||||
PaginationDataDto? paginationData = null;
|
||||
if (request.CurrentPage is not null || request.PerPage is not null)
|
||||
paginationData = new PaginationDataDto
|
||||
{
|
||||
CurrentPage = request.CurrentPage ?? 1,
|
||||
PerPage = request.PerPage ?? 200
|
||||
};
|
||||
|
||||
return new GetPlaylistQuery(
|
||||
playlistId,
|
||||
paginationData);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
@@ -23,8 +22,7 @@ public static class PlaylistDetailsDtoMapping
|
||||
data.Playlist.Name,
|
||||
data.Playlist.Description,
|
||||
data.Playlist.Type,
|
||||
[.. data.Entries.Select(entry => entry.ToResponse())],
|
||||
data.Playlist.EntryCount,
|
||||
data.Entries.ToResponses(),
|
||||
data.Playlist.CreatedOnUtc,
|
||||
data.Playlist.UpdatedOnUtc);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Playlists;
|
||||
@@ -48,4 +51,21 @@ public static class PlaylistEntryDtoMapping
|
||||
display.DurationInSeconds,
|
||||
display.CoverPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to a paginated collection of <see cref="PlaylistEntryResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The paginated playlist entry data to be converted.</param>
|
||||
/// <returns>The converted paginated responses.</returns>
|
||||
public static PaginatedResponse<PlaylistEntryResponse> ToResponses(this PaginatedResultDto<PlaylistEntryDto> data)
|
||||
{
|
||||
return new PaginatedResponse<PlaylistEntryResponse>
|
||||
{
|
||||
Data = [.. data.Data.Select(entry => entry.ToResponse())],
|
||||
CurrentPage = data.CurrentPage,
|
||||
PerPage = data.PerPage,
|
||||
Count = data.Count,
|
||||
NumberOfPages = data.NumberOfPages
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for the <see cref="FavoriteMediaKind"/> enumeration.
|
||||
/// </summary>
|
||||
public static class FavoriteMediaKindExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the error that reports that a media item of <paramref name="mediaKind"/> does not exist.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item that was not found.</param>
|
||||
/// <returns>The not found error specific to the media kind, or the not supported error when the media kind cannot be favorited yet.</returns>
|
||||
public static Error ToMediaItemNotFoundError(this FavoriteMediaKind mediaKind)
|
||||
{
|
||||
return mediaKind switch
|
||||
{
|
||||
FavoriteMediaKind.MusicArtist => DomainErrors.Music.ArtistNotFound,
|
||||
FavoriteMediaKind.MusicAlbum => DomainErrors.Music.AlbumNotFound,
|
||||
FavoriteMediaKind.MusicTrack => DomainErrors.Music.TrackNotFound,
|
||||
FavoriteMediaKind.Book => DomainErrors.WrittenContent.BookNotFound,
|
||||
_ => DomainErrors.Favorites.FavoriteMediaKindIsNotSupported
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Command for marking a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media item to favorite.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the media item to favorite.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record AddFavoriteCommand(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
Guid? MediaItemId
|
||||
) : ICommand;
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
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.Favorites;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to mark a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
public class AddFavoriteCommandHandler : ICommandHandler<AddFavoriteCommand, Result<FavoriteResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<AddFavoriteCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteCommandHandler"/> 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="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public AddFavoriteCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<AddFavoriteCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to mark a media item as a favorite 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 favorite of the current user on the media item, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<FavoriteResponse>> HandleAsync(AddFavoriteCommand 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 media kind is a defined value and the media item identifier is a non-empty Guid before this point.
|
||||
FavoriteMediaKind mediaKind = command.MediaKind!.Value;
|
||||
Guid mediaItemId = command.MediaItemId!.Value;
|
||||
|
||||
// A planned media kind has no catalogued library to look the item up in, so it is rejected before any lookup.
|
||||
if (!Favorite.IsSupported(mediaKind))
|
||||
return DomainErrors.Favorites.FavoriteMediaKindIsNotSupported;
|
||||
|
||||
// The item must exist, and its library must be reachable by the current user, so another user's library cannot be probed through favorites.
|
||||
Result<Guid?> getLibraryIdResult = await _unitOfWork.FavoriteRepository.GetMediaItemLibraryIdAsync(mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryIdResult.IsFailure)
|
||||
return getLibraryIdResult.Errors;
|
||||
if (getLibraryIdResult.Value is null)
|
||||
return mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// An item whose library is not reachable is reported exactly like a missing item, so the response cannot be used to probe whether an item exists in another user's library.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(getLibraryIdResult.Value.Value), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return mediaKind.ToMediaItemNotFoundError();
|
||||
|
||||
// Adding an item that is already a favorite is idempotent: the existing favorite is returned and no event is raised.
|
||||
Result<FavoriteEntity?> getExistingFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getExistingFavoriteResult.IsFailure)
|
||||
return getExistingFavoriteResult.Errors;
|
||||
if (getExistingFavoriteResult.Value is not null)
|
||||
return getExistingFavoriteResult.Value.ToResponse();
|
||||
|
||||
Result<Favorite> createFavoriteResult = Favorite.Create(UserId.Create(userId), MediaItemId.Create(mediaItemId), mediaKind);
|
||||
if (createFavoriteResult.IsFailure)
|
||||
return createFavoriteResult.Errors;
|
||||
Favorite favorite = createFavoriteResult.Value;
|
||||
|
||||
Result<Created> insertResult = await _unitOfWork.FavoriteRepository.InsertAsync(favorite.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
return insertResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
{
|
||||
// A concurrent request favorited the same item between the read above and this write, and the unique index rejected this one. The
|
||||
// desired state already holds, so the request succeeds with the stored favorite, without announcing a favorite that this request did not create.
|
||||
if (!saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.UniqueConstraintViolation))
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
_unitOfWork.ClearTrackedEntities();
|
||||
Result<FavoriteEntity?> getConcurrentFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getConcurrentFavoriteResult.IsFailure)
|
||||
return getConcurrentFavoriteResult.Errors;
|
||||
if (getConcurrentFavoriteResult.Value is null)
|
||||
return saveChangesResult.Errors;
|
||||
return getConcurrentFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// The persisted row is read back, so the response carries the timestamps the auditing interceptor actually stored.
|
||||
Result<FavoriteEntity?> getFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoriteResult.IsFailure)
|
||||
return getFavoriteResult.Errors;
|
||||
if (getFavoriteResult.Value is null)
|
||||
return DomainErrors.Favorites.FavoriteNotFound;
|
||||
|
||||
return getFavoriteResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+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.Favorites.Commands.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
public class AddFavoriteCommandValidator : AbstractValidator<AddFavoriteCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public AddFavoriteCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.MediaKind)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
RuleFor(command => command.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(command => command.MediaKind is not null);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty)
|
||||
.When(command => command.MediaItemId is not null);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Command for removing a media item from the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The name of the kind of the favorited media item, taken from the route.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the favorited media item, taken from the route.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record RemoveFavoriteCommand(
|
||||
string? MediaKind,
|
||||
string? MediaItemId
|
||||
) : ICommand;
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
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.Favorites;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to remove a media item from the favorites of the current user.
|
||||
/// </summary>
|
||||
public class RemoveFavoriteCommandHandler : ICommandHandler<RemoveFavoriteCommand, Result<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<RemoveFavoriteCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteCommandHandler"/> 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 RemoveFavoriteCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<RemoveFavoriteCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to remove a media item from the favorites 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(RemoveFavoriteCommand 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 values are a defined media kind name and a non-empty Guid before this point.
|
||||
FavoriteMediaKind mediaKind = Enum.Parse<FavoriteMediaKind>(command.MediaKind!, ignoreCase: true);
|
||||
Guid mediaItemId = Guid.Parse(command.MediaItemId!);
|
||||
|
||||
// The favorite is loaded by the current user, the kind and the item, so another user's favorite is never touched. It is loaded so that its
|
||||
// aggregate can raise the removal event before the row is deleted. The library of the item is deliberately not evaluated, so a user can
|
||||
// always remove their own favorite whose item was deleted or is no longer accessible.
|
||||
Result<FavoriteEntity?> getFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: true, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoriteResult.IsFailure)
|
||||
return getFavoriteResult.Errors;
|
||||
// Removing a favorite that is already absent succeeds, so a retry, or another tab that removed it first, does not turn the
|
||||
// caller's removal into an error. Nothing is deleted and no event is raised because this request did not remove anything.
|
||||
if (getFavoriteResult.Value is null)
|
||||
return Result.Deleted;
|
||||
|
||||
Result<Favorite> toDomainEntityResult = getFavoriteResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Favorite favorite = toDomainEntityResult.Value;
|
||||
|
||||
Result<Deleted> removeResult = favorite.Remove();
|
||||
if (removeResult.IsFailure)
|
||||
return removeResult.Errors;
|
||||
|
||||
Result<Deleted> deleteFavoriteResult = await _unitOfWork.FavoriteRepository.DeleteByIdAsync(favorite.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteFavoriteResult.IsFailure)
|
||||
return deleteFavoriteResult.Errors;
|
||||
|
||||
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (saveChangesResult.IsFailure)
|
||||
{
|
||||
// A concurrent request removed the same favorite between the read above and this write, so the row this request tried to delete is already gone. The
|
||||
// desired state already holds, so the request succeeds, without announcing a removal that this request did not perform.
|
||||
if (!saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
|
||||
return saveChangesResult.Errors;
|
||||
|
||||
_unitOfWork.ClearTrackedEntities();
|
||||
Result<FavoriteEntity?> getRemainingFavoriteResult = await _unitOfWork.FavoriteRepository
|
||||
.GetByMediaItemIdForUserAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getRemainingFavoriteResult.IsFailure)
|
||||
return getRemainingFavoriteResult.Errors;
|
||||
if (getRemainingFavoriteResult.Value is not null)
|
||||
return saveChangesResult.Errors;
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
// Queue any domain events, to be published after the request has completed successfully.
|
||||
foreach (IDomainEvent domainEvent in favorite.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return Result.Deleted;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="RemoveFavoriteCommand"/>.
|
||||
/// </summary>
|
||||
public class RemoveFavoriteCommandValidator : AbstractValidator<RemoveFavoriteCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public RemoveFavoriteCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.MediaKind)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
// Only the member names are accepted, so a numeric route value that happens to parse as an enumeration value is rejected.
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => Enum.GetNames<FavoriteMediaKind>().Contains(mediaKind, StringComparer.OrdinalIgnoreCase))
|
||||
.When(command => command.MediaKind is not null && command.MediaKind.Length > 0)
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.Must(mediaItemId => Guid.TryParse(mediaItemId, out Guid parsedMediaItemId) && parsedMediaItemId != Guid.Empty)
|
||||
.When(command => command.MediaItemId is not null && command.MediaItemId.Length > 0)
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Query for finding out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media items to check.</param>
|
||||
/// <param name="MediaItemIds">The unique identifiers of the media items to check.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoriteStatusQuery(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
IReadOnlyList<Guid>? MediaItemIds
|
||||
) : IQuery;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#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.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
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.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to find out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
public class GetFavoriteStatusQueryHandler : IQueryHandler<GetFavoriteStatusQuery, Result<FavoriteStatusResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<GetFavoriteStatusQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusQueryHandler"/> 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 GetFavoriteStatusQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IValidator<GetFavoriteStatusQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to find out which media items of one kind are favorites 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 requested <see cref="FavoriteStatusResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<FavoriteStatusResponse>> HandleAsync(GetFavoriteStatusQuery 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 media kind is a defined value and the identifiers are a non-empty collection of non-empty Guids before this point.
|
||||
FavoriteMediaKind mediaKind = query.MediaKind!.Value;
|
||||
List<Guid> mediaItemIds = [.. query.MediaItemIds!.Distinct()];
|
||||
|
||||
// Only the favorites of the current user are checked, so no library access is evaluated: the answer reveals nothing about other users.
|
||||
Result<IReadOnlyList<Guid>> getFavoritedIdsResult = await _unitOfWork.FavoriteRepository
|
||||
.GetFavoritedMediaItemIdsForUserAsync(userId, mediaKind, mediaItemIds, cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoritedIdsResult.IsFailure)
|
||||
return getFavoritedIdsResult.Errors;
|
||||
|
||||
return new FavoriteStatusResponse(getFavoritedIdsResult.Value);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetFavoriteStatusQuery"/>.
|
||||
/// </summary>
|
||||
public class GetFavoriteStatusQueryValidator : AbstractValidator<GetFavoriteStatusQuery>
|
||||
{
|
||||
private const int MAXIMUM_MEDIA_ITEM_COUNT = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetFavoriteStatusQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.MediaKind)
|
||||
.NotNull()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid);
|
||||
|
||||
RuleFor(query => query.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdsCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.Must(mediaItemIds => mediaItemIds!.Count <= MAXIMUM_MEDIA_ITEM_COUNT)
|
||||
.When(query => query.MediaItemIds is not null)
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdsExceedMaximumCount);
|
||||
|
||||
RuleFor(query => query.MediaItemIds)
|
||||
.Must(mediaItemIds => !mediaItemIds!.Contains(Guid.Empty))
|
||||
.When(query => query.MediaItemIds is not null)
|
||||
.WithError(Errors.Favorites.FavoriteMediaItemIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the favorites of the current user, from the most recently favorited.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of media item to restrict the favorites to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="PaginationData">The object containing the requested pagination data.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoritesQuery(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
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.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a window of the favorites of the current user.
|
||||
/// </summary>
|
||||
public class GetFavoritesQueryHandler : IQueryHandler<GetFavoritesQuery, Result<PaginatedResponse<FavoriteItemResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<GetFavoritesQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesQueryHandler"/> 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 GetFavoritesQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService, IValidator<GetFavoritesQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a window of the favorites 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 requested page of favorites, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PaginatedResponse<FavoriteItemResponse>>> HandleAsync(GetFavoritesQuery 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 favorites are scoped to the current user by the repository.
|
||||
Result<PaginatedResultDto<FavoriteItemDto>> getFavoritesResult = await _unitOfWork.FavoriteRepository
|
||||
.GetAllForUserAsync(userId, query.MediaKind, query.PaginationData, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getFavoritesResult.IsFailure)
|
||||
return getFavoritesResult.Errors;
|
||||
|
||||
// Check the access permissions once for each library that the favorited items might belong to.
|
||||
PaginatedResultDto<FavoriteItemDto> page = getFavoritesResult.Value;
|
||||
List<Guid> libraryIds = [.. page.Data
|
||||
.Select(item => item.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<FavoriteItemDto> items = [];
|
||||
foreach (FavoriteItemDto item in page.Data)
|
||||
{
|
||||
Guid libraryId = item.Display?.LibraryId ?? Guid.Empty;
|
||||
if (libraryId == Guid.Empty || libraryAccess[libraryId])
|
||||
items.Add(item);
|
||||
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.
|
||||
items.Add(item with { Display = null });
|
||||
}
|
||||
page = page with { Data = items };
|
||||
}
|
||||
|
||||
return Result.From(page.ToResponses());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetFavoritesQuery"/>.
|
||||
/// </summary>
|
||||
public class GetFavoritesQueryValidator : AbstractValidator<GetFavoritesQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetFavoritesQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.Favorites.FavoriteMediaKindIsInvalid)
|
||||
.When(query => query.MediaKind is not null);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,11 +2,11 @@
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
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;
|
||||
@@ -94,7 +94,7 @@ public class CreatePlaylistCommandHandler : ICommandHandler<CreatePlaylistComman
|
||||
|
||||
// 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);
|
||||
.GetDetailsForUserAsync(playlist.Id.Value, userId, new PaginationDataDto(), cancellationToken).ConfigureAwait(false);
|
||||
if (getDetailsResult.IsFailure)
|
||||
return getDetailsResult.Errors;
|
||||
if (getDetailsResult.Value is null)
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
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.
|
||||
/// Query for getting a playlist of the current user, together with a page 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}")]
|
||||
/// <param name="PaginationData">The object containing the requested pagination data.</param>
|
||||
[DebuggerDisplay("PlaylistId: {PlaylistId}")]
|
||||
public record GetPlaylistQuery(
|
||||
string? PlaylistId,
|
||||
int Offset = 0,
|
||||
int Limit = PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+4
-4
@@ -70,7 +70,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
|
||||
// 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);
|
||||
.GetDetailsForUserAsync(playlistId, userId, query.PaginationData, cancellationToken).ConfigureAwait(false);
|
||||
if (getPlaylistResult.IsFailure)
|
||||
return getPlaylistResult.Errors;
|
||||
if (getPlaylistResult.Value is null)
|
||||
@@ -78,7 +78,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
|
||||
// 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
|
||||
List<Guid> libraryIds = [.. playlist.Entries.Data
|
||||
.Select(entry => entry.Display?.LibraryId ?? Guid.Empty)
|
||||
.Where(libraryId => libraryId != Guid.Empty)
|
||||
.Distinct()];
|
||||
@@ -93,7 +93,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
if (libraryAccess.Values.Any(canAccessLibrary => !canAccessLibrary))
|
||||
{
|
||||
List<PlaylistEntryDto> entries = [];
|
||||
foreach (PlaylistEntryDto entry in playlist.Entries)
|
||||
foreach (PlaylistEntryDto entry in playlist.Entries.Data)
|
||||
{
|
||||
Guid libraryId = entry.Display?.LibraryId ?? Guid.Empty;
|
||||
if (libraryId == Guid.Empty || libraryAccess[libraryId])
|
||||
@@ -102,7 +102,7 @@ public class GetPlaylistQueryHandler : IQueryHandler<GetPlaylistQuery, Result<Pl
|
||||
// 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 };
|
||||
playlist = playlist with { Entries = playlist.Entries with { Data = entries } };
|
||||
}
|
||||
|
||||
return playlist.ToResponse();
|
||||
|
||||
@@ -25,13 +25,5 @@ public class GetPlaylistQueryValidator : AbstractValidator<GetPlaylistQuery>
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for marking a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media item to favorite. Required.</param>
|
||||
/// <param name="MediaItemId">The Id of the media item to favorite. Required.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record AddFavoriteRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
Guid? MediaItemId
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for finding out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media items to check. Required.</param>
|
||||
/// <param name="MediaItemIds">The Ids of the media items to check, from 1 to 100. Required.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoriteStatusRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
List<Guid>? MediaItemIds
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a window of the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.</param>
|
||||
/// <param name="CurrentPage">The one based page of favorites to return. Optional; defaults to 1 when a page size is provided.</param>
|
||||
/// <param name="PerPage">The number of favorites per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every matching favorite is returned.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public record GetFavoritesRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
int? CurrentPage,
|
||||
int? PerPage
|
||||
);
|
||||
@@ -5,12 +5,12 @@ using System.Diagnostics;
|
||||
namespace Lumina.Contracts.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a window of the entries of a playlist of the current user.
|
||||
/// Represents a request for getting a page 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}")]
|
||||
/// <param name="CurrentPage">The one based page of entries to return. Optional; defaults to 1 when a page size is provided.</param>
|
||||
/// <param name="PerPage">The number of entries per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every entry is returned.</param>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public record GetPlaylistRequest(
|
||||
int? Offset,
|
||||
int? Limit
|
||||
int? CurrentPage,
|
||||
int? PerPage
|
||||
);
|
||||
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for a favorite of the current user together with the display details of the media item it references.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The display fields are generic across media kinds. For a music artist the title is the artist name and there is no collection or
|
||||
/// creator. For a music album the creator is the artist and there is no collection. For a music track the collection is the album and the
|
||||
/// creator is the artist. For a book there is no collection yet, because the series of a book is not catalogued, and the creator is its first author.
|
||||
/// </remarks>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="IsAvailable">Whether the media item still exists and can be accessed by the user. When <see langword="false"/>, every display field is empty.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item is not available.</param>
|
||||
/// <param name="Title">The title of the media item, or an empty string when the item is not available.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public sealed record FavoriteItemResponse(
|
||||
FavoriteMediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
bool IsAvailable,
|
||||
Guid LibraryId,
|
||||
string Title,
|
||||
Guid CollectionId,
|
||||
string CollectionTitle,
|
||||
Guid CreatorId,
|
||||
string CreatorName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response for a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the favorite.</param>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="FavoritedOnUtc">The date and time when the media item was favorited.</param>
|
||||
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public sealed record FavoriteResponse(
|
||||
Guid Id,
|
||||
FavoriteMediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
DateTime FavoritedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a response that tells which of the checked media items are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="FavoritedMediaItemIds">The Ids, among the checked ones, of the media items that are favorites of the current user.</param>
|
||||
[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")]
|
||||
public sealed record FavoriteStatusResponse(
|
||||
IReadOnlyList<Guid> FavoritedMediaItemIds
|
||||
);
|
||||
@@ -1,31 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
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.
|
||||
/// Represents a response for a playlist together with a page of 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="Entries">The ordered entries of the requested page 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}; Window: {Entries.Count}")]
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; Entries: {Entries.Count}")]
|
||||
public sealed record PlaylistResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
IReadOnlyList<PlaylistEntryResponse> Entries,
|
||||
int EntryCount,
|
||||
PaginatedResponse<PlaylistEntryResponse> Entries,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,77 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
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="FavoriteEntity"/> entity.
|
||||
/// </summary>
|
||||
public class FavoriteConfiguration : IEntityTypeConfiguration<FavoriteEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="FavoriteEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<FavoriteEntity> builder)
|
||||
{
|
||||
builder.ToTable("Favorites");
|
||||
builder.HasKey(favorite => favorite.Id);
|
||||
builder.Property(favorite => favorite.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 favorite belongs to the user that created it, and it is removed with that user.
|
||||
builder.HasOne<UserEntity>()
|
||||
.WithMany()
|
||||
.HasForeignKey(favorite => favorite.UserId)
|
||||
.IsRequired()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(favorite => favorite.UserId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(favorite => favorite.MediaKind)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnOrder(2);
|
||||
|
||||
builder.Property(favorite => favorite.MediaItemId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// Audit.
|
||||
builder.Property(favorite => favorite.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(favorite => favorite.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(favorite => favorite.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(favorite => favorite.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
// The referenced media item is kept by kind and Id only, without a foreign key: one table serves every media kind, so no single table
|
||||
// can be referenced, and a favorite survives the deletion of the item it references, so its owner can still see and remove it.
|
||||
// The unique index makes the storage medium the owner of the "one favorite per user and item" invariant: a duplicate is rejected even
|
||||
// when two concurrent adds both pass the existence check of the handler.
|
||||
builder.HasIndex(favorite => new { favorite.UserId, favorite.MediaKind, favorite.MediaItemId })
|
||||
.IsUnique();
|
||||
|
||||
// Enable listing the favorites of a user from the most recently favorited: the first index serves the listing of every kind, and the second one serves the listing restricted to one media kind.
|
||||
builder.HasIndex(favorite => new { favorite.UserId, favorite.CreatedOnUtc });
|
||||
|
||||
builder.HasIndex(favorite => new { favorite.UserId, favorite.MediaKind, favorite.CreatedOnUtc });
|
||||
}
|
||||
}
|
||||
+3766
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsFavorites : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Favorites",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
MediaKind = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
MediaItemId = table.Column<Guid>(type: "TEXT", 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_Favorites", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Favorites_Users_UserId",
|
||||
column: x => x.UserId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Favorites_UserId_CreatedOnUtc",
|
||||
table: "Favorites",
|
||||
columns: new[] { "UserId", "CreatedOnUtc" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Favorites_UserId_MediaKind_CreatedOnUtc",
|
||||
table: "Favorites",
|
||||
columns: new[] { "UserId", "MediaKind", "CreatedOnUtc" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Favorites_UserId_MediaKind_MediaItemId",
|
||||
table: "Favorites",
|
||||
columns: new[] { "UserId", "MediaKind", "MediaItemId" },
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Favorites");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -299,6 +299,54 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.ToTable("Tags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("MediaKind")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId", "CreatedOnUtc");
|
||||
|
||||
b.HasIndex("UserId", "MediaKind", "CreatedOnUtc");
|
||||
|
||||
b.HasIndex("UserId", "MediaKind", "MediaItemId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Favorites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaContributors.MediaContributorEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -2839,6 +2887,15 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Favorites.FavoriteEntity", 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.MediaLibrary.AudioLibrary.MusicLibrary.AlbumContributorEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.AlbumEntity", null)
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DTO.Favorites;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for favorites.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A favorite references its media item by kind and Id without a foreign key, so reading a page of favorites resolves the display data of
|
||||
/// the referenced items with one batched query per media kind present in the page, and a favorite whose item no longer exists is kept
|
||||
/// without display data. Duplicate favorites of the same user on the same item are rejected by the unique (UserId, MediaKind, MediaItemId) index.
|
||||
/// </remarks>
|
||||
internal sealed class FavoriteRepository : IFavoriteRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoriteRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public FavoriteRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new favorite.
|
||||
/// </summary>
|
||||
/// <param name="data">The favorite to add.</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 Task<Result<Created>> InsertAsync(FavoriteEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
// The handler checks whether the user already favorited the item and creates a new favorite with a new Id, so this always adds a
|
||||
// row. A retried or concurrent add that passed the handler's check is rejected by the unique (UserId, MediaKind, MediaItemId)
|
||||
// index when the changes are saved, which is the only check that can observe another request's write.
|
||||
_luminaDbContext.Favorites.Add(data);
|
||||
return Task.FromResult<Result<Created>>(Result.Created);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the favorite identified by <paramref name="id"/>.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the favorite to delete.</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>> DeleteByIdAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
// A handler may already have loaded the same favorite in this unit of work, so the tracked instance is preferred over materializing a second copy.
|
||||
FavoriteEntity? favorite = _luminaDbContext.Favorites.Local.FirstOrDefault(trackedFavorite => trackedFavorite.Id == id);
|
||||
favorite ??= await _luminaDbContext.Favorites.FirstOrDefaultAsync(foundFavorite => foundFavorite.Id == id, cancellationToken).ConfigureAwait(false);
|
||||
if (favorite is null)
|
||||
return DomainErrors.Favorites.FavoriteNotFound;
|
||||
|
||||
_luminaDbContext.Favorites.Remove(favorite);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite of the user identified by <paramref name="userId"/> on the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the favorite must belong to.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entity should be tracked by the persistence medium, so that changes to it 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 favorite, <see langword="null"/> when the user has not favorited the media item, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<FavoriteEntity?>> GetByMediaItemIdForUserAsync(Guid userId, FavoriteMediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a favorite that belongs to another user in the first place.
|
||||
IQueryable<FavoriteEntity> query = _luminaDbContext.Favorites;
|
||||
if (!shouldTrackEntities)
|
||||
query = query.AsNoTracking();
|
||||
return await query
|
||||
.FirstOrDefaultAsync(favorite => favorite.UserId == userId && favorite.MediaKind == mediaKind && favorite.MediaItemId == mediaItemId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library that contains the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if the media item exists.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the Id of the library that contains the media item, <see langword="null"/> when the
|
||||
/// media item does not exist or its kind has no catalogued library yet, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<Guid?>> GetMediaItemLibraryIdAsync(FavoriteMediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken)
|
||||
{
|
||||
// Only the library Id is projected, so the check never materializes the media item. The planned kinds have no catalogue table yet, so they have no library.
|
||||
Guid? libraryId = mediaKind switch
|
||||
{
|
||||
FavoriteMediaKind.MusicArtist => await _luminaDbContext.Artists
|
||||
.AsNoTracking()
|
||||
.Where(artist => artist.Id == mediaItemId)
|
||||
.Select(artist => (Guid?)artist.LibraryId)
|
||||
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
|
||||
FavoriteMediaKind.MusicAlbum => await _luminaDbContext.Albums
|
||||
.AsNoTracking()
|
||||
.Where(album => album.Id == mediaItemId)
|
||||
.Select(album => (Guid?)album.LibraryId)
|
||||
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
|
||||
FavoriteMediaKind.MusicTrack => await _luminaDbContext.Tracks
|
||||
.AsNoTracking()
|
||||
.Where(track => track.Id == mediaItemId)
|
||||
.Select(track => (Guid?)track.LibraryId)
|
||||
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
|
||||
FavoriteMediaKind.Book => await _luminaDbContext.Books
|
||||
.AsNoTracking()
|
||||
.Where(book => book.Id == mediaItemId)
|
||||
.Select(book => (Guid?)book.LibraryId)
|
||||
.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false),
|
||||
_ => null,
|
||||
};
|
||||
return Result<Guid?>.Success(libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the paginated favorites of the user identified by <paramref name="userId"/>, from the most recently favorited, together with the display data of the media items they reference,
|
||||
/// or all the matching favorites when the pagination data is <see langword="null"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are retrieved.</param>
|
||||
/// <param name="mediaKind">The kind of media item to restrict the favorites to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching favorites are returned.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved entities should be tracked by the persistence medium, so that changes to them can be saved. Pass <see langword="false"/> for read-only scenarios, to avoid the tracking overhead.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either a <see cref="PaginatedResultDto{FavoriteItemDto}"/>, or an error.</returns>
|
||||
public async Task<Result<PaginatedResultDto<FavoriteItemDto>>> GetAllForUserAsync(Guid userId, FavoriteMediaKind? mediaKind, PaginationDataDto? paginationData = null, bool shouldTrackEntities = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a favorite that belongs to another user in the first place.
|
||||
IQueryable<FavoriteEntity> favoritesQuery = _luminaDbContext.Favorites;
|
||||
if (!shouldTrackEntities)
|
||||
favoritesQuery = favoritesQuery.AsNoTracking();
|
||||
favoritesQuery = favoritesQuery.Where(favorite => favorite.UserId == userId);
|
||||
if (mediaKind is not null)
|
||||
{
|
||||
FavoriteMediaKind kindFilter = mediaKind.Value;
|
||||
favoritesQuery = favoritesQuery.Where(favorite => favorite.MediaKind == kindFilter);
|
||||
}
|
||||
|
||||
// The Id is the tiebreaker, so favorites created at the same instant keep a stable order between pages.
|
||||
IOrderedQueryable<FavoriteEntity> orderedFavoritesQuery = favoritesQuery
|
||||
.OrderByDescending(favorite => favorite.CreatedOnUtc)
|
||||
.ThenBy(favorite => favorite.Id);
|
||||
|
||||
// If no pagination was requested, return all the favorites of the user.
|
||||
if (paginationData is null)
|
||||
{
|
||||
IReadOnlyList<FavoriteItemDto> allFavorites = await ToFavoriteItemsAsync(orderedFavoritesQuery, cancellationToken).ConfigureAwait(false);
|
||||
return new PaginatedResultDto<FavoriteItemDto>
|
||||
{
|
||||
Data = allFavorites,
|
||||
CurrentPage = 1,
|
||||
PerPage = allFavorites.Count,
|
||||
Count = allFavorites.Count,
|
||||
NumberOfPages = 1
|
||||
};
|
||||
}
|
||||
|
||||
int count = await orderedFavoritesQuery.Select(favorite => favorite.Id).CountAsync(cancellationToken).ConfigureAwait(false);
|
||||
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
|
||||
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
|
||||
|
||||
// Only the requested page is materialized, because a user can favorite any number of items.
|
||||
IQueryable<FavoriteEntity> pageQuery = orderedFavoritesQuery
|
||||
.Skip((currentPage - 1) * paginationData.PerPage)
|
||||
.Take(paginationData.PerPage);
|
||||
IReadOnlyList<FavoriteItemDto> paginatedResult = await ToFavoriteItemsAsync(pageQuery, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new PaginatedResultDto<FavoriteItemDto>
|
||||
{
|
||||
Data = paginatedResult,
|
||||
CurrentPage = currentPage,
|
||||
PerPage = paginationData.PerPage,
|
||||
Count = count,
|
||||
NumberOfPages = numberOfPages
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the display data of the media items referenced by the favorites of <paramref name="favoritesQuery"/>, one query per media kind present.
|
||||
/// </summary>
|
||||
/// <param name="favoritesQuery">The query of the favorites to read the display data for.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The favorites together with the display data of the media items they reference.</returns>
|
||||
private async Task<IReadOnlyList<FavoriteItemDto>> ToFavoriteItemsAsync(IQueryable<FavoriteEntity> favoritesQuery, CancellationToken cancellationToken)
|
||||
{
|
||||
List<FavoriteEntity> favorites = await favoritesQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Dictionary<FavoriteMediaKind, Dictionary<Guid, FavoriteItemDisplayDto>> displayDataByKind = [];
|
||||
foreach (IGrouping<FavoriteMediaKind, FavoriteEntity> kindGroup in favorites.GroupBy(favorite => favorite.MediaKind))
|
||||
{
|
||||
List<Guid> mediaItemIds = [.. kindGroup.Select(favorite => favorite.MediaItemId).Distinct()];
|
||||
displayDataByKind[kindGroup.Key] = await GetDisplayDataAsync(kindGroup.Key, mediaItemIds, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A favorite whose item was deleted is kept with no display data, so its owner can still see and remove it instead of it silently disappearing.
|
||||
List<FavoriteItemDto> items = [];
|
||||
foreach (FavoriteEntity favorite in favorites)
|
||||
{
|
||||
FavoriteItemDisplayDto? display = null;
|
||||
if (displayDataByKind[favorite.MediaKind].TryGetValue(favorite.MediaItemId, out FavoriteItemDisplayDto? foundDisplay))
|
||||
display = foundDisplay;
|
||||
items.Add(new FavoriteItemDto(favorite, display));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Ids, among <paramref name="mediaItemIds"/>, of the media items of kind <paramref name="mediaKind"/> that the user identified by <paramref name="userId"/> has favorited.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose favorites are checked.</param>
|
||||
/// <param name="mediaKind">The kind of the media items.</param>
|
||||
/// <param name="mediaItemIds">The Ids of the media items to check.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the subset of the Ids that are favorites of the user, or an error.</returns>
|
||||
public async Task<Result<IReadOnlyList<Guid>>> GetFavoritedMediaItemIdsForUserAsync(Guid userId, FavoriteMediaKind mediaKind, IReadOnlyCollection<Guid> mediaItemIds, CancellationToken cancellationToken)
|
||||
{
|
||||
Guid[] requestedIds = [.. mediaItemIds];
|
||||
// The unique (UserId, MediaKind, MediaItemId) index serves this lookup, and the caller bounds the number of requested Ids.
|
||||
IReadOnlyList<Guid> favoritedIds = await _luminaDbContext.Favorites
|
||||
.AsNoTracking()
|
||||
.Where(favorite => favorite.UserId == userId && favorite.MediaKind == mediaKind && requestedIds.Contains(favorite.MediaItemId))
|
||||
.Select(favorite => favorite.MediaItemId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.From(favoritedIds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the display data of the media items of kind <paramref name="mediaKind"/> identified by <paramref name="mediaItemIds"/> in one query per bounded chunk.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media items.</param>
|
||||
/// <param name="mediaItemIds">The Ids of the media items whose display data is read.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The display data keyed by media item Id. A media item that no longer exists, or whose kind has no catalogue yet, is absent.</returns>
|
||||
private async Task<Dictionary<Guid, FavoriteItemDisplayDto>> GetDisplayDataAsync(FavoriteMediaKind mediaKind, IReadOnlyCollection<Guid> mediaItemIds, CancellationToken cancellationToken)
|
||||
{
|
||||
if (mediaItemIds.Count == 0)
|
||||
return [];
|
||||
|
||||
// The lookup is split into bounded chunks, so even an unpaginated listing never exceeds the storage parameter limit.
|
||||
const int LOOKUP_CHUNK_SIZE = 500;
|
||||
List<DisplayRow> rows = [];
|
||||
foreach (Guid[] chunk in mediaItemIds.Chunk(LOOKUP_CHUNK_SIZE))
|
||||
rows.AddRange(await GetDisplayRowsAsync(mediaKind, chunk, cancellationToken).ConfigureAwait(false));
|
||||
return rows.ToDictionary(
|
||||
row => row.MediaItemId,
|
||||
row => new FavoriteItemDisplayDto(
|
||||
row.LibraryId,
|
||||
row.Title,
|
||||
row.CollectionId ?? Guid.Empty,
|
||||
row.CollectionTitle ?? string.Empty,
|
||||
row.CreatorId ?? Guid.Empty,
|
||||
row.CreatorName ?? string.Empty,
|
||||
row.CoverPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the display data of one bounded chunk of media items of kind <paramref name="mediaKind"/> in a single query.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of the media items.</param>
|
||||
/// <param name="requestedIds">The bounded chunk of media item Ids whose display data is read.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The display rows of the media items that exist.</returns>
|
||||
private async Task<List<DisplayRow>> GetDisplayRowsAsync(FavoriteMediaKind mediaKind, Guid[] requestedIds, CancellationToken cancellationToken)
|
||||
{
|
||||
List<DisplayRow> rows;
|
||||
switch (mediaKind)
|
||||
{
|
||||
case FavoriteMediaKind.MusicArtist:
|
||||
// The cover of the artist is the cover artwork stored for it, if any, the same one the artist listing exposes.
|
||||
rows = await _luminaDbContext.Artists
|
||||
.AsNoTracking()
|
||||
.Where(artist => requestedIds.Contains(artist.Id))
|
||||
.Select(artist => new DisplayRow(
|
||||
artist.Id,
|
||||
artist.LibraryId,
|
||||
artist.Name,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
_luminaDbContext.MusicArtwork
|
||||
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Artist && artwork.OwnerId == artist.Id && artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case FavoriteMediaKind.MusicAlbum:
|
||||
rows = await (from album in _luminaDbContext.Albums.AsNoTracking()
|
||||
join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id
|
||||
where requestedIds.Contains(album.Id)
|
||||
select new DisplayRow(
|
||||
album.Id,
|
||||
album.LibraryId,
|
||||
album.Title,
|
||||
null,
|
||||
null,
|
||||
artist.Id,
|
||||
artist.Name,
|
||||
_luminaDbContext.MusicArtwork
|
||||
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case FavoriteMediaKind.MusicTrack:
|
||||
// The cover of a track is the one stored for its album, like in the playlist entries.
|
||||
rows = await (from track in _luminaDbContext.Tracks.AsNoTracking()
|
||||
join album in _luminaDbContext.Albums on track.AlbumId equals album.Id
|
||||
join artist in _luminaDbContext.Artists on album.ArtistId equals artist.Id
|
||||
where requestedIds.Contains(track.Id)
|
||||
select new DisplayRow(
|
||||
track.Id,
|
||||
track.LibraryId,
|
||||
track.Title,
|
||||
album.Id,
|
||||
album.Title,
|
||||
artist.Id,
|
||||
artist.Name,
|
||||
_luminaDbContext.MusicArtwork
|
||||
.Where(artwork => artwork.OwnerType == MusicArtworkOwnerType.Album && artwork.OwnerId == album.Id && artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case FavoriteMediaKind.Book:
|
||||
// The book catalogue does not persist series yet, so a book has no collection. The creator is the first author by display name,
|
||||
// the same author the book listing shows, and the Id is the tiebreaker between authors that share a display name.
|
||||
rows = await _luminaDbContext.Books
|
||||
.AsNoTracking()
|
||||
.Where(book => requestedIds.Contains(book.Id))
|
||||
.Select(book => new DisplayRow(
|
||||
book.Id,
|
||||
book.LibraryId,
|
||||
book.Title,
|
||||
null,
|
||||
null,
|
||||
(from bookContributor in _luminaDbContext.BookContributors
|
||||
join contributor in _luminaDbContext.MediaContributors on bookContributor.MediaContributorId equals contributor.Id
|
||||
where bookContributor.BookId == book.Id && bookContributor.Role == MediaContributorRole.Author
|
||||
orderby contributor.DisplayName, contributor.Id
|
||||
select (Guid?)contributor.Id).FirstOrDefault(),
|
||||
(from bookContributor in _luminaDbContext.BookContributors
|
||||
join contributor in _luminaDbContext.MediaContributors on bookContributor.MediaContributorId equals contributor.Id
|
||||
where bookContributor.BookId == book.Id && bookContributor.Role == MediaContributorRole.Author
|
||||
orderby contributor.DisplayName, contributor.Id
|
||||
select contributor.DisplayName).FirstOrDefault(),
|
||||
book.Artwork
|
||||
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
|
||||
.Select(artwork => artwork.FileName)
|
||||
.FirstOrDefault()))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The display data of one favorited media item as read from storage, before the absent values are normalized to the generic "no value" form.
|
||||
/// </summary>
|
||||
/// <param name="MediaItemId">The Id of the media item.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
|
||||
/// <param name="Title">The title of the media item.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, if any.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, if any.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, if any.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, if any.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
|
||||
private sealed record DisplayRow(
|
||||
Guid MediaItemId,
|
||||
Guid LibraryId,
|
||||
string Title,
|
||||
Guid? CollectionId,
|
||||
string? CollectionTitle,
|
||||
Guid? CreatorId,
|
||||
string? CreatorName,
|
||||
string? CoverPath
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Dapper;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Playlists;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Playlists;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.DTO.Playlists;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
@@ -169,18 +170,17 @@ internal sealed class PlaylistRepository : IPlaylistRepository
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with a window of the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>.
|
||||
/// Gets the playlist identified by <paramref name="id"/> together with a page of the display details of the media items its entries reference,
|
||||
/// when the playlist belongs to the user identified by <paramref name="userId"/>, or all the entries when the pagination data is <see langword="null"/>.
|
||||
/// </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="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>
|
||||
/// <param name="paginationData">The pagination data that includes the current page and the number of items per page to retrieve. If <see langword="null"/>, all matching entries are returned.</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 and its entry count, <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// An <see cref="Result{TValue}"/> containing either the playlist details and the paginated entries, <see langword="null"/> when no such playlist exists, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, int offset, int limit, CancellationToken cancellationToken)
|
||||
public async Task<Result<PlaylistDetailsDto?>> GetDetailsForUserAsync(Guid id, Guid userId, PaginationDataDto? paginationData = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a playlist that belongs to another user in the first place.
|
||||
PlaylistEntity? playlist = await _luminaDbContext.Playlists
|
||||
@@ -189,16 +189,58 @@ internal sealed class PlaylistRepository : IPlaylistRepository
|
||||
if (playlist is null)
|
||||
return Result<PlaylistDetailsDto?>.Success(null);
|
||||
|
||||
// Only the requested window is materialized. A playlist can hold any number of entries, so the page never loads the whole list.
|
||||
List<PlaylistEntryEntity> windowEntries = await _luminaDbContext.PlaylistEntries
|
||||
IQueryable<PlaylistEntryEntity> entriesQuery = _luminaDbContext.PlaylistEntries
|
||||
.AsNoTracking()
|
||||
.Where(entry => entry.PlaylistId == id)
|
||||
.OrderBy(entry => entry.Position)
|
||||
.Skip(offset)
|
||||
.Take(limit)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
.OrderBy(entry => entry.Position);
|
||||
|
||||
List<Guid> trackIds = [.. windowEntries
|
||||
// If no pagination was requested, return all the entries of the playlist.
|
||||
if (paginationData is null)
|
||||
{
|
||||
IReadOnlyList<PlaylistEntryDto> allEntries = await ToPlaylistEntriesAsync(entriesQuery, offset: 0, cancellationToken).ConfigureAwait(false);
|
||||
return new PlaylistDetailsDto(playlist, new PaginatedResultDto<PlaylistEntryDto>
|
||||
{
|
||||
Data = allEntries,
|
||||
CurrentPage = 1,
|
||||
PerPage = allEntries.Count,
|
||||
Count = allEntries.Count,
|
||||
NumberOfPages = 1
|
||||
});
|
||||
}
|
||||
|
||||
int count = await entriesQuery.Select(entry => entry.Id).CountAsync(cancellationToken).ConfigureAwait(false);
|
||||
int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
|
||||
int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages)); // Make sure current page doesn't exceed maximum number of pages.
|
||||
int offset = (currentPage - 1) * paginationData.PerPage;
|
||||
|
||||
// Only the requested page is materialized. A playlist can hold any number of entries, so the page never loads the whole list.
|
||||
IQueryable<PlaylistEntryEntity> pageQuery = entriesQuery
|
||||
.Skip(offset)
|
||||
.Take(paginationData.PerPage);
|
||||
IReadOnlyList<PlaylistEntryDto> paginatedResult = await ToPlaylistEntriesAsync(pageQuery, offset, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new PlaylistDetailsDto(playlist, new PaginatedResultDto<PlaylistEntryDto>
|
||||
{
|
||||
Data = paginatedResult,
|
||||
CurrentPage = currentPage,
|
||||
PerPage = paginationData.PerPage,
|
||||
Count = count,
|
||||
NumberOfPages = numberOfPages
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the display data of the tracks referenced by the entries of <paramref name="entriesQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="entriesQuery">The ordered query of the entries to read the display data for.</param>
|
||||
/// <param name="offset">The zero based position of the first entry of the page, used to compute the dense display position.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The entries together with the display data of the tracks they reference.</returns>
|
||||
private async Task<IReadOnlyList<PlaylistEntryDto>> ToPlaylistEntriesAsync(IQueryable<PlaylistEntryEntity> entriesQuery, int offset, CancellationToken cancellationToken)
|
||||
{
|
||||
List<PlaylistEntryEntity> entries = await entriesQuery.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
List<Guid> trackIds = [.. entries
|
||||
.Where(entry => entry.MediaItemType == PlaylistMediaItemType.MusicTrack)
|
||||
.Select(entry => entry.MediaItemId)
|
||||
.Distinct()];
|
||||
@@ -206,15 +248,14 @@ internal sealed class PlaylistRepository : IPlaylistRepository
|
||||
|
||||
// An entry whose track was deleted is kept with no display data, so its owner can still see and remove it instead of it silently
|
||||
// disappearing from the playlist. The sparse order key is converted to a dense display position for the response.
|
||||
List<PlaylistEntryDto> entries = [];
|
||||
for (int index = 0; index < windowEntries.Count; index++)
|
||||
List<PlaylistEntryDto> items = [];
|
||||
for (int index = 0; index < entries.Count; index++)
|
||||
{
|
||||
PlaylistEntryEntity entry = windowEntries[index];
|
||||
PlaylistEntryEntity entry = entries[index];
|
||||
displayDataByTrackId.TryGetValue(entry.MediaItemId, out PlaylistEntryDisplayDto? displayData);
|
||||
entries.Add(new PlaylistEntryDto(entry, displayData, offset + index));
|
||||
items.Add(new PlaylistEntryDto(entry, displayData, offset + index));
|
||||
}
|
||||
|
||||
return new PlaylistDetailsDto(playlist, entries);
|
||||
return items;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
@@ -53,6 +54,7 @@ public class LuminaDbContext : DbContext
|
||||
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
|
||||
public virtual DbSet<FavoriteEntity> Favorites { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
@@ -13,6 +14,7 @@ using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.DataAccess.Core.Repositories.Authorization;
|
||||
using Lumina.DataAccess.Core.Repositories.BookLibrary;
|
||||
using Lumina.DataAccess.Core.Repositories.Favorites;
|
||||
using Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
using Lumina.DataAccess.Core.Repositories.MediaContributors;
|
||||
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
@@ -68,6 +70,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private IUserSettingsRepository? _userSettingsRepository;
|
||||
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
|
||||
private IPlaylistRepository? _playlistRepository;
|
||||
private IFavoriteRepository? _favoriteRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the permission repository.
|
||||
@@ -402,6 +405,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the favorite repository.
|
||||
/// </summary>
|
||||
public IFavoriteRepository FavoriteRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_favoriteRepository ??= new FavoriteRepository(_luminaDbContext);
|
||||
return _favoriteRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media item that can be marked as a favorite.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
MusicArtist,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an album of a music library.
|
||||
/// </summary>
|
||||
MusicAlbum,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a track of a music library.
|
||||
/// </summary>
|
||||
MusicTrack,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a book of a book library.
|
||||
/// </summary>
|
||||
Book,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited.
|
||||
/// </summary>
|
||||
Video,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited.
|
||||
/// </summary>
|
||||
Photo,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Common.Errors;
|
||||
|
||||
/// <summary>
|
||||
/// Favorite error types.
|
||||
/// </summary>
|
||||
public static partial class Errors
|
||||
{
|
||||
public static class Favorites
|
||||
{
|
||||
public static Error FavoriteNotFound => Error.NotFound(description: nameof(FavoriteNotFound));
|
||||
public static Error FavoriteAlreadyExists => Error.Conflict(description: nameof(FavoriteAlreadyExists));
|
||||
public static Error FavoriteMediaKindIsInvalid => Error.Validation(description: nameof(FavoriteMediaKindIsInvalid));
|
||||
public static Error FavoriteMediaKindIsNotSupported => Error.Validation(description: nameof(FavoriteMediaKindIsNotSupported));
|
||||
public static Error FavoriteMediaItemIdCannotBeEmpty => Error.Validation(description: nameof(FavoriteMediaItemIdCannotBeEmpty));
|
||||
public static Error FavoriteMediaItemIdsCannotBeEmpty => Error.Validation(description: nameof(FavoriteMediaItemIdsCannotBeEmpty));
|
||||
public static Error FavoriteMediaItemIdsExceedMaximumCount => Error.Validation(description: nameof(FavoriteMediaItemIdsExceedMaximumCount));
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,5 @@ public static partial class Errors
|
||||
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));
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a media item, declared by the favorite bounded context to keep the reference to the catalogue decoupled.
|
||||
/// </summary>
|
||||
[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;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a user, duplicated from the UserManagement bounded context to keep the cross bounded context references decoupled.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class UserId : EntityId<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private UserId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="UserId"/> instance.</returns>
|
||||
public static UserId CreateUnique()
|
||||
{
|
||||
return new UserId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="UserId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="UserId"/> instance.</param>
|
||||
/// <returns>The created <see cref="UserId"/> instance.</returns>
|
||||
public static UserId Create(Guid value)
|
||||
{
|
||||
return new UserId(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;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event raised when a media item is marked as a favorite.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="FavoriteId">The unique identifier of the favorite.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that favorited the media item.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the favorited media item.</param>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("FavoriteId: {FavoriteId.Value}; UserId: {UserId.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")]
|
||||
public record FavoriteAddedDomainEvent(
|
||||
Guid Id,
|
||||
FavoriteId FavoriteId,
|
||||
UserId UserId,
|
||||
MediaItemId MediaItemId,
|
||||
FavoriteMediaKind MediaKind,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event raised when a media item is removed from the favorites.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="FavoriteId">The unique identifier of the favorite.</param>
|
||||
/// <param name="UserId">The unique identifier of the user that owned the favorite.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the media item that was unfavorited.</param>
|
||||
/// <param name="MediaKind">The kind of the media item that was unfavorited.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("FavoriteId: {FavoriteId.Value}; UserId: {UserId.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")]
|
||||
public record FavoriteRemovedDomainEvent(
|
||||
Guid Id,
|
||||
FavoriteId FavoriteId,
|
||||
UserId UserId,
|
||||
MediaItemId MediaItemId,
|
||||
FavoriteMediaKind MediaKind,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// Aggregate root for a favorite, the marker a user places on a media item.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id.Value}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId.Value}")]
|
||||
public sealed class Favorite : AggregateRoot<FavoriteId>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the object representing the unique identifier of the user that owns the favorite.
|
||||
/// </summary>
|
||||
public UserId UserId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the favorited media item.
|
||||
/// </summary>
|
||||
public MediaItemId MediaItemId { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kind of the favorited media item.
|
||||
/// </summary>
|
||||
public FavoriteMediaKind MediaKind { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the favorite was marked for removal in this unit of work.
|
||||
/// </summary>
|
||||
public bool IsRemoved { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Favorite"/> class.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of the favorite.</param>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns the favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="createdOnUtc">The date and time when the favorite was created.</param>
|
||||
/// <param name="updatedOnUtc">The date and time when the favorite was last updated.</param>
|
||||
private Favorite(
|
||||
FavoriteId id,
|
||||
UserId userId,
|
||||
MediaItemId mediaItemId,
|
||||
FavoriteMediaKind mediaKind,
|
||||
DateTime createdOnUtc,
|
||||
Optional<DateTime> updatedOnUtc) : base(id)
|
||||
{
|
||||
Id = id;
|
||||
UserId = userId;
|
||||
MediaItemId = mediaItemId;
|
||||
MediaKind = mediaKind;
|
||||
CreatedOnUtc = createdOnUtc;
|
||||
UpdatedOnUtc = updatedOnUtc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new favorite of the media item identified by <paramref name="mediaItemId"/> for the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns the favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to favorite.</param>
|
||||
/// <param name="mediaKind">The kind of the media item to favorite.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Favorite"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Favorite> Create(UserId userId, MediaItemId mediaItemId, FavoriteMediaKind mediaKind)
|
||||
{
|
||||
// A planned media kind is part of the model so the storage and the contracts are ready for it, but its items cannot be favorited until its library exists.
|
||||
if (!IsSupported(mediaKind))
|
||||
return Errors.Favorites.FavoriteMediaKindIsNotSupported;
|
||||
|
||||
DateTime occurredOnUtc = DateTime.UtcNow;
|
||||
Favorite favorite = new(
|
||||
FavoriteId.CreateUnique(),
|
||||
userId,
|
||||
mediaItemId,
|
||||
mediaKind,
|
||||
occurredOnUtc,
|
||||
Optional<DateTime>.None());
|
||||
|
||||
favorite._domainEvents.Add(new FavoriteAddedDomainEvent(
|
||||
Guid.NewGuid(),
|
||||
favorite.Id,
|
||||
userId,
|
||||
mediaItemId,
|
||||
mediaKind,
|
||||
occurredOnUtc));
|
||||
return favorite;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="Favorite"/> class, with pre-existing data.
|
||||
/// </summary>
|
||||
/// <param name="id">The object representing the unique identifier of the favorite.</param>
|
||||
/// <param name="userId">The object representing the unique identifier of the user that owns the favorite.</param>
|
||||
/// <param name="mediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="mediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="createdOnUtc">The date and time when the favorite was created.</param>
|
||||
/// <param name="updatedOnUtc">The date and time when the favorite was last updated.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully created <see cref="Favorite"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<Favorite> Create(
|
||||
FavoriteId id,
|
||||
UserId userId,
|
||||
MediaItemId mediaItemId,
|
||||
FavoriteMediaKind mediaKind,
|
||||
DateTime createdOnUtc,
|
||||
Optional<DateTime> updatedOnUtc)
|
||||
{
|
||||
// A stored favorite is rehydrated as it was stored, whether or not its media kind is supported today.
|
||||
return new Favorite(id, userId, mediaItemId, mediaKind, createdOnUtc, updatedOnUtc);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the favorite as removed, raising the domain event that announces its removal.
|
||||
/// </summary>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Result<Deleted> Remove()
|
||||
{
|
||||
if (IsRemoved)
|
||||
return Result.Deleted;
|
||||
|
||||
// Earlier events become irrelevant once the favorite is removed.
|
||||
_domainEvents.Clear();
|
||||
IsRemoved = true;
|
||||
_domainEvents.Add(new FavoriteRemovedDomainEvent(
|
||||
Guid.NewGuid(),
|
||||
Id,
|
||||
UserId,
|
||||
MediaItemId,
|
||||
MediaKind,
|
||||
DateTime.UtcNow));
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether media items of <paramref name="mediaKind"/> can be favorited today.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">The kind of media item.</param>
|
||||
/// <returns><see langword="true"/> if items of the media kind can be favorited, <see langword="false"/> otherwise.</returns>
|
||||
public static bool IsSupported(FavoriteMediaKind mediaKind)
|
||||
{
|
||||
return mediaKind switch
|
||||
{
|
||||
FavoriteMediaKind.MusicArtist => true,
|
||||
FavoriteMediaKind.MusicAlbum => true,
|
||||
FavoriteMediaKind.MusicTrack => true,
|
||||
FavoriteMediaKind.Book => true,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Models.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.FavoriteBoundedContext.FavoriteAggregate.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
/// Value Object for the Id of a favorite.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{Value}")]
|
||||
public sealed class FavoriteId : EntityId<Guid>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FavoriteId"/> class.
|
||||
/// </summary>
|
||||
/// <param name="value">The value representing this object.</param>
|
||||
private FavoriteId(Guid value) : base(value)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FavoriteId"/> class.
|
||||
/// </summary>
|
||||
/// <returns>The created <see cref="FavoriteId"/> instance.</returns>
|
||||
public static FavoriteId CreateUnique()
|
||||
{
|
||||
return new FavoriteId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="FavoriteId"/> class, from a pre-existing <paramref name="value"/>.
|
||||
/// </summary>
|
||||
/// <param name="value">The value used to create the <see cref="FavoriteId"/> instance.</param>
|
||||
/// <returns>The created <see cref="FavoriteId"/> instance.</returns>
|
||||
public static FavoriteId Create(Guid value)
|
||||
{
|
||||
return new FavoriteId(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Lumina.Presentation.Api.Common.Routes.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of the favorite routes of the API.
|
||||
/// </summary>
|
||||
public static partial class ApiRoutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Routes for the favorites of the current user.
|
||||
/// </summary>
|
||||
public static class Favorites
|
||||
{
|
||||
public const string GET_FAVORITES = "/users/me/favorites";
|
||||
public const string ADD_FAVORITE = "/users/me/favorites";
|
||||
public const string REMOVE_FAVORITE = "/users/me/favorites/{mediaKind}/{mediaItemId}";
|
||||
public const string GET_FAVORITE_STATUS = "/users/me/favorites/status";
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Core.Favorites.Commands.AddFavorite;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/favorites</c> route, for adding a favorite.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class AddFavoriteEndpoint : BaseEndpoint<AddFavoriteRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<AddFavoriteCommand, Result<FavoriteResponse>> _addFavoriteCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="addFavoriteCommandHandler">Injected service for handling add favorite commands.</param>
|
||||
public AddFavoriteEndpoint(ICommandHandler<AddFavoriteCommand, Result<FavoriteResponse>> addFavoriteCommandHandler)
|
||||
{
|
||||
_addFavoriteCommandHandler = addFavoriteCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.POST);
|
||||
Routes(ApiRoutes.Favorites.ADD_FAVORITE);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the kind and the Id of the media item to favorite.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(AddFavoriteRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
|
||||
// responses, and every response varies by the bearer token that authorized it.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
Result<FavoriteResponse> result = await _addFavoriteCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.AddFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="AddFavoriteEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AddFavoriteEndpointSummary : Summary<AddFavoriteEndpoint, AddFavoriteRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddFavoriteEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public AddFavoriteEndpointSummary()
|
||||
{
|
||||
Summary = "Marks a media item as a favorite of the current user.";
|
||||
Description = "Marks the media item identified by its kind and its Id as a favorite of the currently authenticated user. The supported kinds are MusicArtist, MusicAlbum, MusicTrack and Book. The kinds Video and Photo exist but are planned: they are rejected with a validation error until video and photo libraries are catalogued. The media item must exist and belong to a media library the current user can access; an item that does not exist and an item of a library the user cannot access are reported with the same not found error, so the response cannot be used to find out what another user holds. The operation is idempotent: adding an item that is already a favorite returns the existing favorite and changes nothing.";
|
||||
|
||||
ExampleRequest = new AddFavoriteRequest(
|
||||
MediaKind: FavoriteMediaKind.MusicTrack,
|
||||
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")
|
||||
);
|
||||
RequestParam(request => request.MediaKind, "The kind of the media item to favorite. Required. One of MusicArtist, MusicAlbum, MusicTrack or Book.");
|
||||
RequestParam(request => request.MediaItemId, "The Id of the media item to favorite. Required.");
|
||||
|
||||
ResponseParam<FavoriteResponse>(response => response.Id, "The Id of the favorite.");
|
||||
ResponseParam<FavoriteResponse>(response => response.MediaKind, "The kind of the favorited media item.");
|
||||
ResponseParam<FavoriteResponse>(response => response.MediaItemId, "The Id of the favorited media item.");
|
||||
ResponseParam<FavoriteResponse>(response => response.FavoritedOnUtc, "The date and time when the media item was favorited.");
|
||||
|
||||
Response(200, "The media item is a favorite of the current user, and the favorite is returned.",
|
||||
example: new FavoriteResponse(
|
||||
Id: Guid.Parse("4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"),
|
||||
MediaKind: FavoriteMediaKind.MusicTrack,
|
||||
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
FavoritedOnUtc: new DateTime(2026, 10, 21, 12, 0, 0, DateTimeKind.Utc)
|
||||
)
|
||||
);
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = "/api/v1/users/me/favorites"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = "/api/v1/users/me/favorites"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/users/me/favorites"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the media item does not exist, or it belongs to a media library the current user cannot access. The error names the kind of the media item.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "ArtistNotFound",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "AlbumNotFound",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "TrackNotFound",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "BookNotFound",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(409, "The request failed because the favorite could not be stored, because the database is busy or locked. Repeating the request is safe.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "ConcurrencyConflict",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"FavoriteMediaKindIsInvalid",
|
||||
"FavoriteMediaItemIdCannotBeEmpty",
|
||||
"FavoriteMediaKindIsNotSupported"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavoriteStatus;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/favorites/status</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class GetFavoriteStatusEndpoint : BaseEndpoint<GetFavoriteStatusRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetFavoriteStatusQuery, Result<FavoriteStatusResponse>> _getFavoriteStatusQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getFavoriteStatusQueryHandler">Injected service for handling get favorite status queries.</param>
|
||||
public GetFavoriteStatusEndpoint(IQueryHandler<GetFavoriteStatusQuery, Result<FavoriteStatusResponse>> getFavoriteStatusQueryHandler)
|
||||
{
|
||||
_getFavoriteStatusQueryHandler = getFavoriteStatusQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.GET);
|
||||
Routes(ApiRoutes.Favorites.GET_FAVORITE_STATUS);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the media kind and the Ids of the media items to check.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(GetFavoriteStatusRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
|
||||
// responses, and every response varies by the bearer token that authorized it.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
Result<FavoriteStatusResponse> result = await _getFavoriteStatusQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavoriteStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetFavoriteStatusEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoriteStatusEndpointSummary : Summary<GetFavoriteStatusEndpoint, GetFavoriteStatusRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public GetFavoriteStatusEndpointSummary()
|
||||
{
|
||||
Summary = "Finds out which media items are favorites of the current user.";
|
||||
Description = "Checks up to 100 media items of one kind and returns the Ids, among the checked ones, that are favorites of the currently authenticated user. The media item Ids are sent by repeating the mediaItemIds query parameter once per Id, and the limit of 100 keeps the request line within the size limit of the server. Only the favorites of the current user are consulted, so the answer reveals nothing about the media items of other users. An Id that does not exist, or that is not a favorite, is simply absent from the answer.";
|
||||
|
||||
ExampleRequest = new GetFavoriteStatusRequest(
|
||||
MediaKind: FavoriteMediaKind.MusicTrack,
|
||||
MediaItemIds:
|
||||
[
|
||||
Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
Guid.Parse("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d")
|
||||
]
|
||||
);
|
||||
RequestParam(request => request.MediaKind, "The kind of the media items to check. Required. One of MusicArtist, MusicAlbum, MusicTrack or Book.");
|
||||
RequestParam(request => request.MediaItemIds, "The Ids of the media items to check, from 1 to 100, sent as a repeated query parameter. Required.");
|
||||
|
||||
ResponseParam<FavoriteStatusResponse>(response => response.FavoritedMediaItemIds, "The Ids, among the checked ones, of the media items that are favorites of the current user.");
|
||||
|
||||
Response(200, "The favorite status of the checked media items is returned.",
|
||||
example: new FavoriteStatusResponse(
|
||||
FavoritedMediaItemIds: [Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")]
|
||||
)
|
||||
);
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = "/api/v1/users/me/favorites/status"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = "/api/v1/users/me/favorites/status"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/users/me/favorites/status"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/users/me/favorites/status",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/users/me/favorites/status",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"FavoriteMediaKindIsInvalid",
|
||||
"FavoriteMediaItemIdsCannotBeEmpty",
|
||||
"FavoriteMediaItemIdsExceedMaximumCount",
|
||||
"FavoriteMediaItemIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.Favorites;
|
||||
using Lumina.Application.Core.Favorites.Queries.GetFavorites;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/favorites</c> route, for getting the favorites.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class GetFavoritesEndpoint : BaseEndpoint<GetFavoritesRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetFavoritesQuery, Result<PaginatedResponse<FavoriteItemResponse>>> _getFavoritesQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getFavoritesQueryHandler">Injected service for handling get favorites queries.</param>
|
||||
public GetFavoritesEndpoint(IQueryHandler<GetFavoritesQuery, Result<PaginatedResponse<FavoriteItemResponse>>> getFavoritesQueryHandler)
|
||||
{
|
||||
_getFavoritesQueryHandler = getFavoritesQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.GET);
|
||||
Routes(ApiRoutes.Favorites.GET_FAVORITES);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a page of the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the optional media kind filter and the page bounds.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(GetFavoritesRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
|
||||
// responses, and every response varies by the bearer token that authorized it.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
Result<PaginatedResponse<FavoriteItemResponse>> result = await _getFavoritesQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Favorites;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Favorites;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.GetFavorites;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetFavoritesEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetFavoritesEndpointSummary : Summary<GetFavoritesEndpoint, GetFavoritesRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetFavoritesEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public GetFavoritesEndpointSummary()
|
||||
{
|
||||
Summary = "Gets the favorites of the current user.";
|
||||
Description = "Gets the favorites of the currently authenticated user, from the most recently favorited, across every kind of media item or restricted to one kind. The currentPage and perPage query parameters select the page, and count reports the number of favorites that match the filter. When neither parameter is provided, every matching favorite is returned in a single page. Each favorite carries the display details of the media item it references: the title, the collection, the creator and the cover art. A favorite whose media item was deleted, or whose media library the user can no longer access, is still returned, with isAvailable set to false and empty display details, so the user can see it and remove it. A favorite of another user is never returned.";
|
||||
|
||||
ExampleRequest = new GetFavoritesRequest(
|
||||
MediaKind: FavoriteMediaKind.MusicTrack,
|
||||
CurrentPage: 1,
|
||||
PerPage: 200
|
||||
);
|
||||
RequestParam(request => request.MediaKind, "The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.");
|
||||
RequestParam(request => request.CurrentPage, "The one based page of favorites to return. Optional; defaults to 1 when a page size is provided.");
|
||||
RequestParam(request => request.PerPage, "The number of favorites per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every matching favorite is returned.");
|
||||
|
||||
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.Data, "The favorites of the requested page, from the most recently favorited.");
|
||||
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.CurrentPage, "The current page number.");
|
||||
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.PerPage, "The number of favorites retrieved per page.");
|
||||
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.Count, "The total number of favorites that match the filter.");
|
||||
ResponseParam<PaginatedResponse<FavoriteItemResponse>>(response => response.NumberOfPages, "The total number of pages.");
|
||||
|
||||
ResponseParam<FavoriteItemResponse>(response => response.MediaKind, "The kind of the favorited media item.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.MediaItemId, "The Id of the favorited media item.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.IsAvailable, "Whether the media item still exists and its library is accessible to the current user.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.LibraryId, "The Id of the media library that contains the media item.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.Title, "The title of the media item.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.CollectionId, "The Id of the collection that contains the media item, or the empty Guid when there is none.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.CreatorId, "The Id of the creator of the media item, or the empty Guid when there is none.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none.");
|
||||
ResponseParam<FavoriteItemResponse>(response => response.CoverPath, "The path of the cover art of the media item, if available.");
|
||||
|
||||
Response(200, "The favorites of the current user are returned.",
|
||||
example: new PaginatedResponse<FavoriteItemResponse>
|
||||
{
|
||||
Data =
|
||||
[
|
||||
new FavoriteItemResponse(
|
||||
MediaKind: FavoriteMediaKind.MusicTrack,
|
||||
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
IsAvailable: true,
|
||||
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
|
||||
Title: "The Show Must Go On",
|
||||
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
|
||||
CollectionTitle: "Innuendo",
|
||||
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
|
||||
CreatorName: "Queen",
|
||||
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg"
|
||||
),
|
||||
new FavoriteItemResponse(
|
||||
MediaKind: FavoriteMediaKind.Book,
|
||||
MediaItemId: Guid.Parse("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"),
|
||||
IsAvailable: true,
|
||||
LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"),
|
||||
Title: "The Fellowship of the Ring",
|
||||
CollectionId: Guid.Empty,
|
||||
CollectionTitle: string.Empty,
|
||||
CreatorId: Guid.Parse("8e9f0a1b-2c3d-4e4f-9a5b-6c7d8e9f0a1b"),
|
||||
CreatorName: "J. R. R. Tolkien",
|
||||
CoverPath: "/artwork/books/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/cover.jpg"
|
||||
),
|
||||
new FavoriteItemResponse(
|
||||
MediaKind: FavoriteMediaKind.MusicAlbum,
|
||||
MediaItemId: Guid.Parse("9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c"),
|
||||
IsAvailable: false,
|
||||
LibraryId: Guid.Empty,
|
||||
Title: string.Empty,
|
||||
CollectionId: Guid.Empty,
|
||||
CollectionTitle: string.Empty,
|
||||
CreatorId: Guid.Empty,
|
||||
CreatorName: string.Empty,
|
||||
CoverPath: null
|
||||
)
|
||||
],
|
||||
CurrentPage = 1,
|
||||
PerPage = 200,
|
||||
Count = 3,
|
||||
NumberOfPages = 1
|
||||
}
|
||||
);
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = "/api/v1/users/me/favorites"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = "/api/v1/users/me/favorites"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/users/me/favorites"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/users/me/favorites",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"FavoriteMediaKindIsInvalid"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Favorites.Commands.RemoveFavorite;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Favorites;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/favorites/{mediaKind}/{mediaItemId}</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<RemoveFavoriteCommand, Result<Deleted>> _removeFavoriteCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="removeFavoriteCommandHandler">Injected service for handling remove favorite commands.</param>
|
||||
public RemoveFavoriteEndpoint(ICommandHandler<RemoveFavoriteCommand, Result<Deleted>> removeFavoriteCommandHandler)
|
||||
{
|
||||
_removeFavoriteCommandHandler = removeFavoriteCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.DELETE);
|
||||
Routes(ApiRoutes.Favorites.REMOVE_FAVORITE);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a media item from the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The favorites belong to the authenticated user, so no intermediary may store any response of this route, including its problem
|
||||
// responses, and every response varies by the bearer token that authorized it.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
// Take the kind and the unique identifier of the media item from the route, as raw strings so the validator reports a clean error for an unparseable value.
|
||||
string? mediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString();
|
||||
string? mediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString();
|
||||
Result<Deleted> result = await _removeFavoriteCommandHandler.HandleAsync(new RemoveFavoriteCommand(mediaKind, mediaItemId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Favorites.RemoveFavorite;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="RemoveFavoriteEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class RemoveFavoriteEndpointSummary : Summary<RemoveFavoriteEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public RemoveFavoriteEndpointSummary()
|
||||
{
|
||||
Summary = "Removes a media item from the favorites of the current user.";
|
||||
Description = "Removes the media item identified by its kind and its Id from the favorites of the currently authenticated user. The kind is the name of a kind of media item, such as MusicTrack, and is matched without regard to case. The media item itself is never deleted. The favorite is always the one of the authenticated user, so this route can never remove another user's favorite. The media library of the item is deliberately not checked, so a user can always remove their own favorite whose item was deleted or is no longer accessible. Removing is idempotent: an item that is not a favorite of the user already has the desired state, so the request succeeds without changing anything and without raising an event.";
|
||||
|
||||
Params["mediaKind"] = "The name of the kind of media item, matched case insensitively: MusicArtist, MusicAlbum, MusicTrack or Book.";
|
||||
Params["mediaItemId"] = "The Id of the media item to remove from the favorites.";
|
||||
|
||||
Response(200, "The media item was successfully removed from the favorites.");
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(409, "The request failed because the database is busy or locked, or the favorite was changed by another request in a way that could not be reconciled. Removing a favorite that another request removed first succeeds.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "ConcurrencyConflict",
|
||||
instance = "/api/v1/users/me/favorites/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/users/me/favorites/Unknown/not-a-guid",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"FavoriteMediaKindIsInvalid",
|
||||
"FavoriteMediaItemIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
@@ -37,8 +38,7 @@ public class CreatePlaylistEndpointSummary : Summary<CreatePlaylistEndpoint, Cre
|
||||
ResponseParam<PlaylistResponse>(response => response.Name, "The name of the playlist.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Description, "The description of the playlist, if applicable.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Type, "The kind of media the playlist holds.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Entries, "The ordered entries of the playlist.");
|
||||
ResponseParam<PlaylistResponse>(response => response.EntryCount, "The total number of entries the playlist holds, even when only a window of them is returned.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Entries, "The page of ordered entries of the playlist, with its pagination metadata.");
|
||||
ResponseParam<PlaylistResponse>(response => response.CreatedOnUtc, "The date and time when the playlist was created.");
|
||||
ResponseParam<PlaylistResponse>(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable.");
|
||||
|
||||
@@ -48,8 +48,14 @@ public class CreatePlaylistEndpointSummary : Summary<CreatePlaylistEndpoint, Cre
|
||||
Name: "Evening listening",
|
||||
Description: "Quiet tracks for the end of the day.",
|
||||
Type: PlaylistType.Music,
|
||||
Entries: [],
|
||||
EntryCount: 0,
|
||||
Entries: new PaginatedResponse<PlaylistEntryResponse>
|
||||
{
|
||||
Data = [],
|
||||
CurrentPage = 1,
|
||||
PerPage = 200,
|
||||
Count = 0,
|
||||
NumberOfPages = 0
|
||||
},
|
||||
CreatedOnUtc: new DateTime(2026, 10, 21, 12, 0, 0, DateTimeKind.Utc),
|
||||
UpdatedOnUtc: null
|
||||
)
|
||||
|
||||
+3
-8
@@ -1,5 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.Playlists;
|
||||
using Lumina.Application.Core.Playlists.Queries.GetPlaylist;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
@@ -7,7 +8,6 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Playlists;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -45,7 +45,7 @@ public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a window of the entries of a playlist of the current user.
|
||||
/// Gets a page of the entries of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
@@ -57,12 +57,7 @@ public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
// Take the unique identifier from the route.
|
||||
string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString();
|
||||
int offset = request.Offset ?? 0;
|
||||
// The limit bounds one response window, not the size of the playlist. Clamping it keeps a crafted limit from turning the
|
||||
// windowed read into one unbounded response, while the handler still validates the value independently.
|
||||
int limit = Math.Clamp(request.Limit ?? PlaylistWindow.DEFAULT_ENTRY_WINDOW_SIZE, 1, PlaylistWindow.MAXIMUM_ENTRY_WINDOW_SIZE);
|
||||
Result<PlaylistResponse> result = await _getPlaylistQueryHandler
|
||||
.HandleAsync(new GetPlaylistQuery(playlistId, offset, limit), cancellationToken).ConfigureAwait(false);
|
||||
Result<PlaylistResponse> result = await _getPlaylistQueryHandler.HandleAsync(request.ToQuery(playlistId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+32
-27
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.Playlists;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.Playlists;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playlists;
|
||||
using System;
|
||||
@@ -22,21 +23,20 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
|
||||
public GetPlaylistEndpointSummary()
|
||||
{
|
||||
Summary = "Gets a playlist of the current user.";
|
||||
Description = "Gets the playlist identified by its Id when it belongs to the currently authenticated user, together with a window of its ordered entries. The offset and limit query parameters select the window, and entryCount reports the total number of entries. The limit is a response-window bound of at most 1000 entries and does not cap the size of the playlist. Each entry carries the media item Id and the media item kind it references, and a music track also carries the display details needed to play it: the library, album and artist Ids, the title, the album title, the artist name, the duration and the cover art. An entry whose media item was deleted is still returned, with empty display details.";
|
||||
Description = "Gets the playlist identified by its Id when it belongs to the currently authenticated user, together with a page of its ordered entries. The currentPage and perPage query parameters select the page, and entries.count reports the total number of entries. When neither parameter is provided, every entry is returned in a single page. Each entry carries the media item Id and the media item kind it references, and a music track also carries the display details needed to play it: the library, album and artist Ids, the title, the album title, the artist name, the duration and the cover art. An entry whose media item was deleted is still returned, with empty display details.";
|
||||
|
||||
ExampleRequest = new GetPlaylistRequest(
|
||||
Offset: 0,
|
||||
Limit: 200
|
||||
CurrentPage: 1,
|
||||
PerPage: 200
|
||||
);
|
||||
RequestParam(request => request.Offset, "The zero based position of the first entry to return. Optional; defaults to 0.");
|
||||
RequestParam(request => request.Limit, "The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.");
|
||||
RequestParam(request => request.CurrentPage, "The one based page of entries to return. Optional; defaults to 1 when a page size is provided.");
|
||||
RequestParam(request => request.PerPage, "The number of entries per page. Optional; defaults to 200 when a page is provided. When both pagination parameters are omitted, every entry is returned.");
|
||||
|
||||
ResponseParam<PlaylistResponse>(response => response.Id, "The Id of the playlist.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Name, "The name of the playlist.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Description, "The description of the playlist, if applicable.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Type, "The kind of media the playlist holds.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Entries, "The ordered entries of the playlist.");
|
||||
ResponseParam<PlaylistResponse>(response => response.EntryCount, "The total number of entries the playlist holds, even when only a window of them is returned.");
|
||||
ResponseParam<PlaylistResponse>(response => response.Entries, "The page of ordered entries of the playlist, with its pagination metadata.");
|
||||
ResponseParam<PlaylistResponse>(response => response.CreatedOnUtc, "The date and time when the playlist was created.");
|
||||
ResponseParam<PlaylistResponse>(response => response.UpdatedOnUtc, "The date and time when the playlist was last updated, if applicable.");
|
||||
|
||||
@@ -46,24 +46,30 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
|
||||
Name: "Evening listening",
|
||||
Description: "Quiet tracks for the end of the day.",
|
||||
Type: PlaylistType.Music,
|
||||
Entries:
|
||||
[
|
||||
new PlaylistEntryResponse(
|
||||
Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"),
|
||||
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
MediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
Position: 0,
|
||||
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
|
||||
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
|
||||
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
|
||||
MediaItemTitle: "The Show Must Go On",
|
||||
CollectionTitle: "Innuendo",
|
||||
CreatorName: "Queen",
|
||||
DurationInSeconds: 262,
|
||||
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg"
|
||||
)
|
||||
],
|
||||
EntryCount: 1,
|
||||
Entries: new PaginatedResponse<PlaylistEntryResponse>
|
||||
{
|
||||
Data =
|
||||
[
|
||||
new PlaylistEntryResponse(
|
||||
Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"),
|
||||
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
MediaItemType: PlaylistMediaItemType.MusicTrack,
|
||||
Position: 0,
|
||||
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
|
||||
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
|
||||
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
|
||||
MediaItemTitle: "The Show Must Go On",
|
||||
CollectionTitle: "Innuendo",
|
||||
CreatorName: "Queen",
|
||||
DurationInSeconds: 262,
|
||||
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg"
|
||||
)
|
||||
],
|
||||
CurrentPage = 1,
|
||||
PerPage = 200,
|
||||
Count = 1,
|
||||
NumberOfPages = 1
|
||||
},
|
||||
CreatedOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc),
|
||||
UpdatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc)
|
||||
)
|
||||
@@ -124,8 +130,7 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"PlaylistIdCannotBeEmpty",
|
||||
"PlaylistEntryWindowOffsetIsInvalid"
|
||||
"PlaylistIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Binary file not shown.
Binary file not shown.
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight album elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedMusicAlbumLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight album elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MusicAlbumLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight music artist elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedMusicArtistLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight music artist elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MusicArtistLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight track elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedMusicTrackLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight track elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MusicTrackLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a page of elements together with its pagination metadata.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the elements of the page.</typeparam>
|
||||
/// <param name="Data">The elements of the requested page.</param>
|
||||
/// <param name="CurrentPage">The one based number of the returned page.</param>
|
||||
/// <param name="PerPage">The number of elements requested per page.</param>
|
||||
/// <param name="Count">The total number of elements that match the filter, even when only a page of them is returned.</param>
|
||||
/// <param name="NumberOfPages">The total number of pages that match the filter.</param>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}; Count: {Count}")]
|
||||
public sealed record PaginatedDto<T>(
|
||||
List<T> Data,
|
||||
int CurrentPage,
|
||||
int PerPage,
|
||||
int Count,
|
||||
int NumberOfPages
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the favorite.</param>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="FavoritedOnUtc">The date and time when the media item was favorited.</param>
|
||||
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public sealed record FavoriteDto(
|
||||
Guid Id,
|
||||
FavoriteMediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
DateTime FavoritedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a favorite of the current user together with the display details of the media item it references.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="IsAvailable">Whether the media item still exists and can be accessed by the user. When <see langword="false"/>, every display field is empty.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item is not available.</param>
|
||||
/// <param name="Title">The title of the media item, or an empty string when the item is not available.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public sealed record FavoriteItemDto(
|
||||
FavoriteMediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
bool IsAvailable,
|
||||
Guid LibraryId,
|
||||
string Title,
|
||||
Guid CollectionId,
|
||||
string CollectionTitle,
|
||||
Guid CreatorId,
|
||||
string CreatorName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object that tells which of the checked media items are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="FavoritedMediaItemIds">The Ids, among the checked ones, of the media items that are favorites of the current user.</param>
|
||||
[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")]
|
||||
public sealed record FavoriteStatusDto(
|
||||
List<Guid> FavoritedMediaItemIds
|
||||
);
|
||||
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight book elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedBookLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight book elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<BookLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a playlist together with its ordered entries.
|
||||
/// Data transfer object for a playlist together with a page of 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="EntryCount">The number of entries the playlist holds, even when only a window of them is returned.</param>
|
||||
/// <param name="Entries">The ordered entries of the requested window of the playlist.</param>
|
||||
/// <param name="Entries">The page of ordered entries of the playlist, together with its pagination metadata.</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}; Entries: {Entries.Count}")]
|
||||
@@ -24,8 +23,7 @@ public sealed record PlaylistDto(
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
int EntryCount,
|
||||
List<PlaylistEntryDto> Entries,
|
||||
PaginatedDto<PlaylistEntryDto> Entries,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media item that can be marked as a favorite.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
MusicArtist,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an album of a music library.
|
||||
/// </summary>
|
||||
MusicAlbum,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a track of a music library.
|
||||
/// </summary>
|
||||
MusicTrack,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a book of a book library.
|
||||
/// </summary>
|
||||
Book,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited.
|
||||
/// </summary>
|
||||
Video,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited.
|
||||
/// </summary>
|
||||
Photo,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for marking a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media item to favorite. Required.</param>
|
||||
/// <param name="MediaItemId">The Id of the media item to favorite. Required.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record AddFavoriteRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
Guid? MediaItemId
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for finding out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media items to check. Required.</param>
|
||||
/// <param name="MediaItemIds">The Ids of the media items to check, from 1 to 100. Required.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoriteStatusRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
List<Guid>? MediaItemIds
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a page of the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.</param>
|
||||
/// <param name="CurrentPage">The one based page of favorites to return. Optional; defaults to 1.</param>
|
||||
/// <param name="PerPage">The number of favorites per page. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public record GetFavoritesRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
int? CurrentPage,
|
||||
int? PerPage
|
||||
);
|
||||
@@ -5,12 +5,12 @@ using System.Diagnostics;
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a window of the entries of a playlist of the current user.
|
||||
/// Represents a request for getting a page 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}")]
|
||||
/// <param name="CurrentPage">The one based page of entries to return. Optional; defaults to 1.</param>
|
||||
/// <param name="PerPage">The number of entries per page. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public record GetPlaylistRequest(
|
||||
int? Offset,
|
||||
int? Limit
|
||||
int? CurrentPage,
|
||||
int? PerPage
|
||||
);
|
||||
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user